diff --git a/README.md b/README.md index 28761cd7ee78666419dae0a3491b97b59245ed85..647eaa133dcd8a01d4e904947fc4c449bcdcab1f 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,28 @@ func handleRequest(w http.ResponseWriter, r *http.Request) { ``` +### Accept Content Type + +With the `ContentType` function you can negotiate the content type of HTTP request. + +```go +package main + +import ( + "net/http" + "gitlab.schukai.com/oss/libraries/go/network/http-negotiation" +) + +func handleRequest(w http.ResponseWriter, r *http.Request) { + n := negotiation.New(r.Header) + + if n.ContentType("application/json") != "" { + // ... + } + +} +``` + ### Language Negotiation With the `Language` function you can negotiate the language of HTTP request. @@ -66,7 +88,6 @@ func handleRequest(w http.ResponseWriter, r *http.Request) { } } - ``` ### Charset Negotiation @@ -115,6 +136,16 @@ func handleRequest(w http.ResponseWriter, r *http.Request) { ``` +## Changelog + +### 1.1.0 + +* Add `ContentType` function + +### 1.0.0 + +* Initial release + ## Contributing Merge requests are welcome. For major changes, please open an issue first to discuss what diff --git a/api.go b/api.go index 8ae6596856ce7a85a333b14901d00a01f16baf08..fa394b2279e0a31c8c4ae42102179edd55ee65e0 100644 --- a/api.go +++ b/api.go @@ -14,6 +14,11 @@ func New(header http.Header) *Negotiation { return &Negotiation{header} } +func (n *Negotiation) ContentType(acceptance ...string) string { + parser := newHeaderParser(n.header, false) + return parser.selectOffer(acceptance, parser.parse(headerContentType)) +} + // Type returns the most preferred content type from the HTTP Accept header. // If nothing accepted, then empty string is returned. func (n *Negotiation) Type(offers ...string) (bestOffer string) { diff --git a/api_test.go b/api_test.go index a976912a50030b6c29848dbe973b8efe13ae834f..c59933eb39c37faeb9926f7620c3b5e68cfed8c6 100644 --- a/api_test.go +++ b/api_test.go @@ -5,6 +5,24 @@ import ( "testing" ) +func TestContentType(t *testing.T) { + + req, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) + } + + req.Header.Set("Content-Type", "application/json") + + n := New(req.Header) + + if n.ContentType("application/json") != "application/json" { + t.Errorf("handler returned wrong status code: got %v want %v", + n.Type("application/json"), "application/json") + } + +} + func TestNegotiationLanguage(t *testing.T) { req, err := http.NewRequest("GET", "/", nil) diff --git a/header.go b/header.go index c651276e5f39d482ce703b11ff833a260942f155..69bb5b07ce92f388e3c0869aaa841a59d419ab89 100644 --- a/header.go +++ b/header.go @@ -5,4 +5,5 @@ const ( headerAcceptLanguage = "Accept-Language" headerAcceptEncoding = "Accept-Encoding" headerAcceptCharset = "Accept-Charset" + headerContentType = "Content-Type" )