Skip to content

Commit

Permalink
✨ feat: netutil - add new util func ParseAccept() for parse header Ac…
Browse files Browse the repository at this point in the history
…cept
  • Loading branch information
inhere committed Jun 27, 2023
1 parent 9765d6d commit ed6c3af
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
13 changes: 13 additions & 0 deletions netutil/httpheader/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,20 @@ const (

Accept = "Accept"
Cookie = "Cookie"
// Upgrade header. check websocket:
// header["Connection"] == "Upgrade" and header["Upgrade"] == "websocket"
Upgrade = "Upgrade"

AcceptEnc = "Accept-Encoding"
ContentType = "Content-Type"
Connection = "Connection"

XRealIP = "X-Real-IP"

XForwardedFor = "X-Forwarded-For"
XForwardedHost = "X-Forwarded-Host"
XForwardedProto = "X-Forwarded-Proto"

// XRequestedWith header. check ajax: header["X-Requested-With"] == XMLHttpRequest
XRequestedWith = "X-Requested-With"
)
17 changes: 17 additions & 0 deletions netutil/httpreq/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,3 +374,20 @@ func ResponseToString(w *http.Response) string {

return buf.String()
}

// ParseAccept header to strings. referred from gin framework
func ParseAccept(acceptHeader string) []string {
if acceptHeader == "" {
return []string{}
}

parts := strings.Split(acceptHeader, ",")
outs := make([]string, 0, len(parts))

for _, part := range parts {
if part = strings.TrimSpace(strings.Split(part, ";")[0]); part != "" {
outs = append(outs, part)
}
}
return outs
}
13 changes: 13 additions & 0 deletions netutil/httpreq/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,16 @@ func TestMergeURLValues(t *testing.T) {
uv = httpreq.MergeURLValues(nil, url.Values{"key2": []string{"val2"}})
assert.Eq(t, "val2", uv.Get("key2"))
}

func TestParseAccept(t *testing.T) {
// parseAccept
ss := httpreq.ParseAccept("")
assert.Len(t, ss, 0)

ss = httpreq.ParseAccept(",")
assert.Len(t, ss, 0)

ss = httpreq.ParseAccept("application/json")
assert.Len(t, ss, 1)
assert.Eq(t, []string{"application/json"}, ss)
}

0 comments on commit ed6c3af

Please sign in to comment.