Skip to content

Commit

Permalink
Merge pull request #55 from swaggo/mimetype-headers
Browse files Browse the repository at this point in the history
add content-type response headers
  • Loading branch information
ubogdan committed Oct 12, 2021
2 parents 4b2426b + bd37c4b commit 5c56dbb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
15 changes: 14 additions & 1 deletion swagger.go
Expand Up @@ -3,6 +3,7 @@ package httpSwagger
import (
"html/template"
"net/http"
"path/filepath"
"regexp"
"sync"

Expand Down Expand Up @@ -120,6 +121,19 @@ func Handler(configFns ...func(*Config)) http.HandlerFunc {
h.Prefix = matches[1]
})

switch filepath.Ext(path) {
case ".html":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
case ".css":
w.Header().Set("Content-Type", "text/css; charset=utf-8")
case ".js":
w.Header().Set("Content-Type", "application/javascript")
case ".png":
w.Header().Set("Content-Type", "image/png")
case ".json":
w.Header().Set("Content-Type", "application/json; charset=utf-8")
}

switch path {
case "index.html":
_ = index.Execute(w, config)
Expand All @@ -130,7 +144,6 @@ func Handler(configFns ...func(*Config)) http.HandlerFunc {

return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write([]byte(doc))
case "":
http.Redirect(w, r, h.Prefix+"index.html", 301)
Expand Down
18 changes: 14 additions & 4 deletions swagger_test.go
Expand Up @@ -45,6 +45,7 @@ func TestWrapHandler(t *testing.T) {

w1 := performRequest("GET", "/index.html", router)
assert.Equal(t, 200, w1.Code)
assert.Equal(t, w1.Header()["Content-Type"][0], "text/html; charset=utf-8")

w2 := performRequest("GET", "/doc.json", router)
assert.Equal(t, 500, w2.Code)
Expand All @@ -56,12 +57,21 @@ func TestWrapHandler(t *testing.T) {

w3 := performRequest("GET", "/favicon-16x16.png", router)
assert.Equal(t, 200, w3.Code)
assert.Equal(t, w3.Header()["Content-Type"][0], "image/png")

w4 := performRequest("GET", "/notfound", router)
assert.Equal(t, 404, w4.Code)
w4 := performRequest("GET", "/swagger-ui.css", router)
assert.Equal(t, 200, w4.Code)
assert.Equal(t, w4.Header()["Content-Type"][0], "text/css; charset=utf-8")

w5 := performRequest("GET", "/", router)
assert.Equal(t, 301, w5.Code)
w5 := performRequest("GET", "/swagger-ui-bundle.js", router)
assert.Equal(t, 200, w5.Code)
assert.Equal(t, w5.Header()["Content-Type"][0], "application/javascript")

w6 := performRequest("GET", "/notfound", router)
assert.Equal(t, 404, w6.Code)

w7 := performRequest("GET", "/", router)
assert.Equal(t, 301, w7.Code)
}

func performRequest(method, target string, h http.Handler) *httptest.ResponseRecorder {
Expand Down

0 comments on commit 5c56dbb

Please sign in to comment.