feat(form): add custom string slice for form tag unmarshal (#3970)
Resolves #3970
package main
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
type CustomPath []string
func (b *CustomPath) UnmarshalParam(param string) error {
elems := strings.Split(param, "/")
n := len(elems)
if n < 2 {
return fmt.Errorf("invalid path: %s", param)
}
*b = elems
return nil
}
type PathRequest struct {
Paths CustomPath `form:"path"`
}
func main() {
g := gin.Default()
g.GET("", func(c *gin.Context) {
var request PathRequest
if err := c.ShouldBind(&request); err != nil {
c.String(http.StatusBadRequest, "request parse err: %v", err)
return
}
c.String(200, "Hello %s", request.Paths)
})
g.Run(":9000")
}
Calling this server with a string parameters path will get the expected slices.
Example:
$ curl 'http://127.0.0.1:9000?path=hello/world'
CustomPath: [hello world]
format the code for better review.
Codecov Report
All modified and coverable lines are covered by tests :white_check_mark:
Project coverage is 99.05%. Comparing base (
3dc1cd6) to head (5e4591f). Report is 59 commits behind head on master.
Additional details and impacted files
@@ Coverage Diff @@
## master #3971 +/- ##
==========================================
- Coverage 99.21% 99.05% -0.16%
==========================================
Files 42 44 +2
Lines 3182 2755 -427
==========================================
- Hits 3157 2729 -428
+ Misses 17 15 -2
- Partials 8 11 +3
| Flag | Coverage Δ | |
|---|---|---|
? |
||
| -tags "sonic avx" | 99.04% <100.00%> (?) |
|
| -tags go_json | 99.04% <100.00%> (?) |
|
| -tags nomsgpack | 99.04% <100.00%> (?) |
|
| go-1.18 | ? |
|
| go-1.19 | ? |
|
| go-1.20 | ? |
|
| go-1.21 | 99.05% <100.00%> (-0.16%) |
:arrow_down: |
| go-1.22 | 99.05% <100.00%> (?) |
|
| macos-latest | 99.05% <100.00%> (-0.16%) |
:arrow_down: |
| ubuntu-latest | 99.05% <100.00%> (-0.16%) |
:arrow_down: |
Flags with carried forward coverage won't be shown. Click here to find out more.
:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.
please add test case
please add test case
Test cases have been added, please review them again. Thank you.
Is it possible to add this for arrays as well? A use case for me would be converting a UUID to a binary uuid, which is a [16]byte
Is it possible to add this for arrays as well? A use case for me would be converting a UUID to a binary uuid, which is a
[16]byte
Yes. There will be some custom arrays for business purposes, such as Mongo's ObjectID, which is a [12]byte.