Skip to content

Commit

Permalink
✨ feat(net/ctype): add new util func for check content-type
Browse files Browse the repository at this point in the history
- ToKind()
  • Loading branch information
inhere committed Mar 16, 2023
1 parent d6255ee commit a995df0
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 2 deletions.
5 changes: 3 additions & 2 deletions netutil/httpctype/content_type.go
Expand Up @@ -9,13 +9,13 @@ const (
HTML = "text/html; charset=utf-8"

Text = "text/plain; charset=utf-8" // equals Plain
Plain = "text/plain; charset=utf-8"
Plain = Text

XML2 = "text/xml; charset=utf-8"
XML = "application/xml; charset=utf-8"

YML = "application/x-yaml; charset=utf-8"
YAML = "application/x-yaml; charset=utf-8"
YML = YAML

JSON = "application/json; charset=utf-8"
JSONP = "application/javascript; charset=utf-8" // equals to JS
Expand All @@ -25,6 +25,7 @@ const (

MSGPACK = "application/x-msgpack; charset=utf-8"
MSGPACK2 = "application/msgpack; charset=utf-8"

PROTOBUF = "application/x-protobuf"

Form = "application/x-www-form-urlencoded"
Expand Down
9 changes: 9 additions & 0 deletions netutil/httpctype/kind.go
@@ -0,0 +1,9 @@
package httpctype

// there commonly base type category list
const (
KindForm = "form"
KindFormData = "dataForm"
KindJSON = "json"
KindXML = "xml"
)
33 changes: 33 additions & 0 deletions netutil/httpctype/util.go
@@ -0,0 +1,33 @@
package httpctype

import "strings"

// ToKind name match
func ToKind(cType, defaultType string) string {
if len(cType) == 0 {
return defaultType
}

// JSON body request: "application/json"
if strings.Contains(cType, "/json") {
return KindJSON
}

// basic POST form data binding. content type: "application/x-www-form-urlencoded"
if strings.Contains(cType, "/x-www-form-urlencoded") {
return KindForm
}

// contains file uploaded form: "multipart/form-data" "multipart/mixed"
// strings.HasPrefix(mediaType, "multipart/")
if strings.Contains(cType, "/form-data") {
return KindFormData
}

// XML body request: "text/xml"
if strings.Contains(cType, "/xml") {
return KindXML
}

return defaultType
}
28 changes: 28 additions & 0 deletions netutil/httpctype/util_test.go
@@ -0,0 +1,28 @@
package httpctype_test

import (
"testing"

"github.com/gookit/goutil/netutil/httpctype"
"github.com/gookit/goutil/testutil/assert"
)

func TestToKind(t *testing.T) {
tests := []struct {
cType string
defaultType string
want string
}{
{"", "abc", "abc"},
{"not-match", "", ""},
{"not-match", "abc", "abc"},
{httpctype.JSON, "", httpctype.KindJSON},
{httpctype.Form, "", httpctype.KindForm},
{httpctype.FormData, "", httpctype.KindFormData},
{httpctype.XML, "", httpctype.KindXML},
}

for _, tt := range tests {
assert.Equal(t, tt.want, httpctype.ToKind(tt.cType, tt.defaultType))
}
}

0 comments on commit a995df0

Please sign in to comment.