mirror of https://github.com/gin-gonic/gin.git
binding: support []byte
* form1.go ```golang package main import ( "fmt" "github.com/gin-gonic/gin" ) type testForm struct { Mode string `form:"mode"` Text string `form:"text"` Voice []byte `form:"voice"` Voice2 []byte `form:"voice2"` } func main() { router := gin.Default() router.POST("/test.form", func(c *gin.Context) { t2 := testForm{} if err := c.ShouldBind(&t2); err != nil { fmt.Printf("err = %s:%v\n", err, t2) c.JSON(500, gin.H{"err": err.Error()}) return } c.JSON(200, t2) }) router.Run() } //client /* curl -F mode=A -F text="test" -F voice=@form1.go -F voice2="voice" 127.0.0.1:8080/test.form|jq { "Mode": "A", "Text": "test", "Voice": "cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKCSJnaXRodWIuY29tL2dpbi1nb25pYy9naW4iCikKCnR5cGUgdGVzdEZvcm0gc3RydWN0IHsKCU1vZGUgICBzdHJpbmcgYGZvcm06Im1vZGUiYAoJVGV4dCAgIHN0cmluZyBgZm9ybToidGV4dCJgCglWb2ljZSAgW11ieXRlIGBmb3JtOiJ2b2ljZSJgCglWb2ljZTIgW11ieXRlIGBmb3JtOiJ2b2ljZTIiYAp9CgpmdW5jIG1haW4oKSB7Cglyb3V0ZXIgOj0gZ2luLkRlZmF1bHQoKQoJcm91dGVyLlBPU1QoIi90ZXN0LmZvcm0iLCBmdW5jKGMgKmdpbi5Db250ZXh0KSB7CgoJCXQyIDo9IHRlc3RGb3Jte30KCQlpZiBlcnIgOj0gYy5TaG91bGRCaW5kKCZ0Mik7IGVyciAhPSBuaWwgewoJCQlmbXQuUHJpbnRmKCJlcnIgPSAlczoldlxuIiwgZXJyLCB0MikKCQkJYy5KU09OKDUwMCwgZ2luLkh7ImVyciI6IGVyci5FcnJvcigpfSkKCQkJcmV0dXJuCgkJfQoJCWMuSlNPTigyMDAsIHQyKQoJfSkKCglyb3V0ZXIuUnVuKCkKfQo=", "Voice2": "dm9pY2U=" } */ ```
This commit is contained in:
parent
5612cadb73
commit
5b9692dc3b
|
@ -146,6 +146,15 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
|
|||
if !ok {
|
||||
vs = []string{opt.defaultValue}
|
||||
}
|
||||
|
||||
switch value.Interface().(type) {
|
||||
case []byte:
|
||||
if len(vs) > 0 {
|
||||
value.Set(reflect.ValueOf([]byte(vs[0])))
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return true, setSlice(vs, value, field)
|
||||
case reflect.Array:
|
||||
if !ok {
|
||||
|
|
|
@ -6,6 +6,7 @@ package binding
|
|||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
@ -39,6 +40,22 @@ func setByMultipartFormFile(value reflect.Value, field reflect.StructField, file
|
|||
return true, nil
|
||||
}
|
||||
case reflect.Slice:
|
||||
switch value.Interface().(type) {
|
||||
case []byte:
|
||||
fd, err := files[0].Open()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer fd.Close()
|
||||
c, err := ioutil.ReadAll(fd)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
value.Set(reflect.ValueOf(c))
|
||||
return true, nil
|
||||
}
|
||||
|
||||
slice := reflect.MakeSlice(value.Type(), len(files), len(files))
|
||||
isSetted, err = setArrayOfMultipartFormFiles(slice, field, files)
|
||||
if err != nil || !isSetted {
|
||||
|
|
Loading…
Reference in New Issue