Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support default value for form #1138

Merged
merged 11 commits into from
Apr 25, 2018
17 changes: 16 additions & 1 deletion binding/form_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"reflect"
"strconv"
"strings"
"time"
)

Expand All @@ -23,6 +24,15 @@ func mapForm(ptr interface{}, form map[string][]string) error {

structFieldKind := structField.Kind()
inputFieldName := typeField.Tag.Get("form")
inputFieldNameList := strings.Split(inputFieldName, ",")
inputFieldName = inputFieldNameList[0]
var defaultValue interface{}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any need to cast it as interface{}? As I see below, you'll always use it as string and parse it to the specific type, right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, use string, thanks!

if len(inputFieldNameList) > 1 {
defaultList := strings.Split(inputFieldNameList[1], "=")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe use strings.SplitN(inputFieldNameList[1], "=", 2) and remove the condition below len(defaultList) == 2 . as it is right now, is also ok.

https://golang.org/pkg/strings/#SplitN

Copy link
Member Author

@thinkerou thinkerou Oct 24, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we should use SplitN which can reduce some codes(interface{} and len(defaultList)==2). Thx!

if len(defaultList) == 2 && defaultList[0] == "default" {
defaultValue = defaultList[1]
}
}
if inputFieldName == "" {
inputFieldName = typeField.Name

Expand All @@ -38,8 +48,13 @@ func mapForm(ptr interface{}, form map[string][]string) error {
}
}
inputValue, exists := form[inputFieldName]

if !exists {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if inputValue is empty array(inputField exist and its ""), default value not take effect

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you post one example? thanks!

continue
if defaultValue.(string) == "" {
continue
}
inputValue = make([]string, 1)
inputValue[0] = defaultValue.(string)
}

numElems := len(inputValue)
Expand Down