Skip to content

Commit

Permalink
add Header from struct function
Browse files Browse the repository at this point in the history
  • Loading branch information
Jirawat Harnsiriwatanakit committed Jan 25, 2020
1 parent d25f6f0 commit ae0ae39
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
9 changes: 9 additions & 0 deletions req.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func (h Header) Clone() Header {
return hh
}

// ParseStruct parse struct into header
func ParseStruct(h Header, v interface{}) Header {
data, err := json.Marshal(v)
if err != nil {
Expand All @@ -58,6 +59,14 @@ func ParseStruct(h Header, v interface{}) Header {
return h
}

// HeaderFromStruct init header from struct
func HeaderFromStruct(v interface{}) Header {

var header Header
header = ParseStruct(header, v)
return header
}

// Param represents http request param
type Param map[string]interface{}

Expand Down
22 changes: 21 additions & 1 deletion req_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func TestHeader(t *testing.T) {
func TestParseStruct(t *testing.T) {

type HeaderStruct struct {
UserAgent string `json:"User-Agent"`
UserAgent string `json:"User-Agent"`
Authorization string `json:"Authorization"`
}

Expand All @@ -282,6 +282,26 @@ func TestParseStruct(t *testing.T) {
var header Header
header = ParseStruct(header, h)

if header["User-Agent"] != "V1.0.0" && header["Authorization"] != "roc" {
t.Fatal("struct parser for header is not working")
}

}

func TestHeaderFromStruct(t *testing.T) {

type HeaderStruct struct {
UserAgent string `json:"User-Agent"`
Authorization string `json:"Authorization"`
}

h := HeaderStruct{
"V1.0.0",
"roc",
}

header := HeaderFromStruct(h)

if header["User-Agent"] != "V1.0.0" && header["Authorization"] != "roc" {
t.Fatal("struct parser for header is not working")
}
Expand Down

0 comments on commit ae0ae39

Please sign in to comment.