Skip to content

Commit

Permalink
Merge pull request #5 from gwvandesteeg/add-mime-method
Browse files Browse the repository at this point in the history
Add MIME() to exclude parameters in generated string
  • Loading branch information
elnormous authored May 9, 2022
2 parents 79542e9 + 574da8b commit dcd30b1
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
13 changes: 13 additions & 0 deletions contenttype.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
35 changes: 35 additions & 0 deletions contenttype_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package contenttype_test

import (
"errors"
"fmt"
"log"
"net/http"
"reflect"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit dcd30b1

Please sign in to comment.