feat: add httpc.Parse (#1698)
This commit is contained in:
27
rest/internal/encoding/parser.go
Normal file
27
rest/internal/encoding/parser.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package encoding
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/mapping"
|
||||
)
|
||||
|
||||
const headerKey = "header"
|
||||
|
||||
var headerUnmarshaler = mapping.NewUnmarshaler(headerKey, mapping.WithStringValues(),
|
||||
mapping.WithCanonicalKeyFunc(textproto.CanonicalMIMEHeaderKey))
|
||||
|
||||
// ParseHeaders parses the headers request.
|
||||
func ParseHeaders(header http.Header, v interface{}) error {
|
||||
m := map[string]interface{}{}
|
||||
for k, v := range header {
|
||||
if len(v) == 1 {
|
||||
m[k] = v[0]
|
||||
} else {
|
||||
m[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
return headerUnmarshaler.Unmarshal(m, v)
|
||||
}
|
||||
40
rest/internal/encoding/parser_test.go
Normal file
40
rest/internal/encoding/parser_test.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package encoding
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseHeaders(t *testing.T) {
|
||||
var val struct {
|
||||
Foo string `header:"foo"`
|
||||
Baz int `header:"baz"`
|
||||
Qux bool `header:"qux,default=true"`
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodGet, "/any", nil)
|
||||
r.Header.Set("foo", "bar")
|
||||
r.Header.Set("baz", "1")
|
||||
assert.Nil(t, ParseHeaders(r.Header, &val))
|
||||
assert.Equal(t, "bar", val.Foo)
|
||||
assert.Equal(t, 1, val.Baz)
|
||||
assert.True(t, val.Qux)
|
||||
}
|
||||
|
||||
func TestParseHeadersMulti(t *testing.T) {
|
||||
var val struct {
|
||||
Foo []string `header:"foo"`
|
||||
Baz int `header:"baz"`
|
||||
Qux bool `header:"qux,default=true"`
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodGet, "/any", nil)
|
||||
r.Header.Set("foo", "bar")
|
||||
r.Header.Add("foo", "bar1")
|
||||
r.Header.Set("baz", "1")
|
||||
assert.Nil(t, ParseHeaders(r.Header, &val))
|
||||
assert.Equal(t, []string{"bar", "bar1"}, val.Foo)
|
||||
assert.Equal(t, 1, val.Baz)
|
||||
assert.True(t, val.Qux)
|
||||
}
|
||||
Reference in New Issue
Block a user