diff --git a/contenttype.go b/contenttype.go index 6551215..f7f469d 100644 --- a/contenttype.go +++ b/contenttype.go @@ -300,6 +300,19 @@ func (mediaType *MediaType) String() string { return stringBuilder.String() } +// MIME returns the MIME type without any of the parameters +func (mediaType MediaType) MIME() string { + var stringBuilder strings.Builder + + if len(mediaType.Type) > 0 || len(mediaType.Subtype) > 0 { + stringBuilder.WriteString(mediaType.Type) + stringBuilder.WriteByte('/') + stringBuilder.WriteString(mediaType.Subtype) + } + + return stringBuilder.String() +} + // GetMediaType gets the content of Content-Type header, parses it, and returns the parsed MediaType. // If the request does not contain the Content-Type header, an empty MediaType is returned. func GetMediaType(request *http.Request) (MediaType, error) { diff --git a/contenttype_test.go b/contenttype_test.go index 14b4283..56601ff 100644 --- a/contenttype_test.go +++ b/contenttype_test.go @@ -2,6 +2,7 @@ package contenttype_test import ( "errors" + "fmt" "log" "net/http" "reflect" @@ -110,6 +111,40 @@ func TestString(t *testing.T) { } } +func TestMediaType_MIME(t *testing.T) { + testCases := []struct { + name string + value contenttype.MediaType + result string + }{ + {name: "Empty media type", value: contenttype.MediaType{}, result: ""}, + {name: "Type and subtype", value: contenttype.MediaType{Type: "application", Subtype: "json", Parameters: contenttype.Parameters{}}, result: "application/json"}, + {name: "Type, subtype, parameter", value: contenttype.MediaType{Type: "a", Subtype: "b", Parameters: contenttype.Parameters{"c": "d"}}, result: "a/b"}, + } + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + result := testCase.value.MIME() + + if result != testCase.result { + t.Errorf("Invalid result type, got %s, exptected %s", result, testCase.result) + } + }) + } +} + +// ExampleMediaType_MIME comparing to MIME types +func ExampleMediaType_MIME() { + mt := contenttype.NewMediaType("application/json; charset=utf-8") + fmt.Printf("MIME(): %s\n", mt.MIME()) + fmt.Printf("matches: application/json: %v\n", mt.MIME() == "application/json") + fmt.Printf("matches: application/*: %v\n", mt.MIME() == "application/*") + fmt.Printf("matches: text/plain: %v\n", mt.MIME() == "text/plain") + // Output: MIME(): application/json + // matches: application/json: true + // matches: application/*: false + // matches: text/plain: false +} + func TestGetMediaType(t *testing.T) { testCases := []struct { name string