Skip to content

Commit

Permalink
add content-type response headers (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
ubogdan authored Oct 12, 2021
1 parent 0c8bf3f commit 2c359ae
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
14 changes: 13 additions & 1 deletion swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package echoSwagger
import (
"html/template"
"net/http"
"path/filepath"
"regexp"
"sync"

Expand Down Expand Up @@ -82,6 +83,18 @@ func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
h.Prefix = matches[1]
})


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

defer c.Response().Flush()
switch path {
case "":
Expand All @@ -96,7 +109,6 @@ func EchoWrapHandler(configFns ...func(c *Config)) echo.HandlerFunc {
return nil
}

c.Response().Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = c.Response().Writer.Write([]byte(doc))
default:
h.ServeHTTP(c.Response().Writer, c.Request())
Expand Down
19 changes: 13 additions & 6 deletions swagger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,14 +232,13 @@ func (s *mockedSwag) ReadDoc() string {
}

func TestWrapHandler(t *testing.T) {

router := echo.New()

//RegisterEchoHandler(router.GET, "/", nil)
router.GET("/*", EchoWrapHandler(DocExpansion("none"), DomID("#swagger-ui")))

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 @@ -251,11 +250,19 @@ func TestWrapHandler(t *testing.T) {
w3 := performRequest("GET", "/favicon-16x16.png", router)
assert.Equal(t, 200, w3.Code)

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", "/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)

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

func performRequest(method, target string, e *echo.Echo) *httptest.ResponseRecorder {
Expand Down

0 comments on commit 2c359ae

Please sign in to comment.