예제 #1
0
func parseTag(t string) (*tag, error) {
	found, value, err := structtag.Extract("inject", t)
	if err != nil {
		return nil, err
	}
	if !found {
		return nil, nil
	}
	if value == "" {
		return injectOnly, nil
	}
	if value == "inline" {
		return injectInline, nil
	}
	if value == "private" {
		return injectPrivate, nil
	}
	return &tag{Name: value}, nil
}
예제 #2
0
// CheckRequired checks whether all fields marked as required have value
func (request *FormRequest) CheckRequired(destination interface{}) error {
	rvalue := reflect.ValueOf(destination).Elem()
	typ := rvalue.Type()
	for i := 0; i < rvalue.NumField(); i++ {
		required, _, err := structtag.Extract("required", string(typ.Field(i).Tag))

		if err != nil {
			return NewInternalServerError(
				"Error extracting tag using structtag",
				map[string]interface{}{"error": err},
			)
		}

		if required {
			name := typ.Field(i).Tag.Get("name")
			if request.HTTPRequest.PostFormValue(name) == "" {
				return NewMissingParameter(name)
			}
		}
	}
	return nil
}
예제 #3
0
func TestExtract(t *testing.T) {
	cases := []struct {
		Name  string // Input name
		Tag   string // Input tag
		Found bool   // Expected found status
		Value string // Expected value
		Error bool   // Indicates if an error is expected
	}{
		{
			Name:  "inject",
			Tag:   `inject:`,
			Error: true,
		},
		{
			Name:  "inject",
			Tag:   `inject:"`,
			Error: true,
		},
		{
			Name:  "inject",
			Tag:   `inject:""`,
			Found: true,
		},
		{
			Name:  "inject",
			Tag:   `inject:"a"`,
			Found: true,
			Value: "a",
		},
		{
			Name:  "inject",
			Tag:   ` inject:"a"`,
			Found: true,
			Value: "a",
		},
		{
			Name: "inject",
			Tag:  `  `,
		},
		{
			Name:  "inject",
			Tag:   `inject:"\"a"`,
			Found: true,
			Value: `"a`,
		},
	}

	for _, e := range cases {
		found, value, err := structtag.Extract(e.Name, e.Tag)

		if !e.Error && err != nil {
			t.Fatalf("unexpected error %s for case %+v", err, e)
		}
		if e.Error && err == nil {
			t.Fatalf("did not get expected error for case %+v", e)
		}

		if found != e.Found {
			if e.Found {
				t.Fatalf("did not find value when expecting to %+v", e)
			} else {
				t.Fatalf("found value when not expecting to %+v", e)
			}
		}

		if value != e.Value {
			t.Fatalf(`found unexpected value "%s" for %+v`, value, e)
		}
	}
}