diff --git a/swagger.go b/swagger.go index cf778c1..8487a0e 100644 --- a/swagger.go +++ b/swagger.go @@ -3,6 +3,7 @@ package echoSwagger import ( "html/template" "net/http" + "path/filepath" "regexp" "sync" @@ -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 "": @@ -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()) diff --git a/swagger_test.go b/swagger_test.go index 3d4da53..4c52abe 100644 --- a/swagger_test.go +++ b/swagger_test.go @@ -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) @@ -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 {