From 05a9350e5776bd39a13cc146e1dd2380b53459b8 Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Mon, 20 Nov 2017 09:40:03 +0100 Subject: [PATCH] Use contants from http package. --- api/dashboard.go | 4 +-- api/debug.go | 2 +- api/handler.go | 24 +++++++------- healthcheck/healthcheck.go | 6 ++-- integration/consul_test.go | 4 +-- integration/docker_test.go | 4 +-- integration/https_test.go | 4 +-- integration/websocket_test.go | 4 +-- metrics/prometheus.go | 4 ++- middlewares/accesslog/logger_test.go | 2 +- middlewares/error_pages_test.go | 14 ++++---- middlewares/retry.go | 2 +- middlewares/retry_test.go | 2 +- ping/ping.go | 2 +- provider/rest/rest.go | 48 +++++++++++++++------------- version/version.go | 4 +-- 16 files changed, 68 insertions(+), 62 deletions(-) diff --git a/api/dashboard.go b/api/dashboard.go index 268b179af..80dc9309e 100644 --- a/api/dashboard.go +++ b/api/dashboard.go @@ -14,10 +14,10 @@ type DashboardHandler struct{} // AddRoutes add dashboard routes on a router func (g DashboardHandler) AddRoutes(router *mux.Router) { // Expose dashboard - router.Methods("GET").Path("/").HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + router.Methods(http.MethodGet).Path("/").HandlerFunc(func(response http.ResponseWriter, request *http.Request) { http.Redirect(response, request, "/dashboard/", 302) }) - router.Methods("GET").PathPrefix("/dashboard/"). + router.Methods(http.MethodGet).PathPrefix("/dashboard/"). Handler(http.StripPrefix("/dashboard/", http.FileServer(&assetfs.AssetFS{Asset: autogen.Asset, AssetInfo: autogen.AssetInfo, AssetDir: autogen.AssetDir, Prefix: "static"}))) } diff --git a/api/debug.go b/api/debug.go index 61db00a8f..6ed0f8fa9 100644 --- a/api/debug.go +++ b/api/debug.go @@ -22,7 +22,7 @@ type DebugHandler struct{} // AddRoutes add debug routes on a router func (g DebugHandler) AddRoutes(router *mux.Router) { - router.Methods("GET").Path("/debug/vars"). + router.Methods(http.MethodGet).Path("/debug/vars"). HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") fmt.Fprint(w, "{\n") diff --git a/api/handler.go b/api/handler.go index 0420039db..f9510c072 100644 --- a/api/handler.go +++ b/api/handler.go @@ -36,20 +36,20 @@ func (p Handler) AddRoutes(router *mux.Router) { DebugHandler{}.AddRoutes(router) } - router.Methods("GET").Path("/api").HandlerFunc(p.getConfigHandler) - router.Methods("GET").Path("/api/providers").HandlerFunc(p.getConfigHandler) - router.Methods("GET").Path("/api/providers/{provider}").HandlerFunc(p.getProviderHandler) - router.Methods("GET").Path("/api/providers/{provider}/backends").HandlerFunc(p.getBackendsHandler) - router.Methods("GET").Path("/api/providers/{provider}/backends/{backend}").HandlerFunc(p.getBackendHandler) - router.Methods("GET").Path("/api/providers/{provider}/backends/{backend}/servers").HandlerFunc(p.getServersHandler) - router.Methods("GET").Path("/api/providers/{provider}/backends/{backend}/servers/{server}").HandlerFunc(p.getServerHandler) - router.Methods("GET").Path("/api/providers/{provider}/frontends").HandlerFunc(p.getFrontendsHandler) - router.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}").HandlerFunc(p.getFrontendHandler) - router.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}/routes").HandlerFunc(p.getRoutesHandler) - router.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}/routes/{route}").HandlerFunc(p.getRouteHandler) + router.Methods(http.MethodGet).Path("/api").HandlerFunc(p.getConfigHandler) + router.Methods(http.MethodGet).Path("/api/providers").HandlerFunc(p.getConfigHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}").HandlerFunc(p.getProviderHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/backends").HandlerFunc(p.getBackendsHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/backends/{backend}").HandlerFunc(p.getBackendHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/backends/{backend}/servers").HandlerFunc(p.getServersHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/backends/{backend}/servers/{server}").HandlerFunc(p.getServerHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/frontends").HandlerFunc(p.getFrontendsHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/frontends/{frontend}").HandlerFunc(p.getFrontendHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/frontends/{frontend}/routes").HandlerFunc(p.getRoutesHandler) + router.Methods(http.MethodGet).Path("/api/providers/{provider}/frontends/{frontend}/routes/{route}").HandlerFunc(p.getRouteHandler) // health route - router.Methods("GET").Path("/health").HandlerFunc(p.getHealthHandler) + router.Methods(http.MethodGet).Path("/health").HandlerFunc(p.getHealthHandler) version.Handler{}.AddRoutes(router) diff --git a/healthcheck/healthcheck.go b/healthcheck/healthcheck.go index d578b98d0..d0dcadd75 100644 --- a/healthcheck/healthcheck.go +++ b/healthcheck/healthcheck.go @@ -132,7 +132,7 @@ func checkBackend(currentBackend *BackendHealthCheck) { func (backend *BackendHealthCheck) newRequest(serverURL *url.URL) (*http.Request, error) { if backend.Port == 0 { - return http.NewRequest("GET", serverURL.String()+backend.Path, nil) + return http.NewRequest(http.MethodGet, serverURL.String()+backend.Path, nil) } // copy the url and add the port to the host @@ -141,7 +141,7 @@ func (backend *BackendHealthCheck) newRequest(serverURL *url.URL) (*http.Request u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(backend.Port)) u.Path = u.Path + backend.Path - return http.NewRequest("GET", u.String(), nil) + return http.NewRequest(http.MethodGet, u.String(), nil) } func checkHealth(serverURL *url.URL, backend *BackendHealthCheck) bool { @@ -159,5 +159,5 @@ func checkHealth(serverURL *url.URL, backend *BackendHealthCheck) bool { if err == nil { defer resp.Body.Close() } - return err == nil && resp.StatusCode == 200 + return err == nil && resp.StatusCode == http.StatusOK } diff --git a/integration/consul_test.go b/integration/consul_test.go index 46bc48d92..066d85dad 100644 --- a/integration/consul_test.go +++ b/integration/consul_test.go @@ -179,7 +179,7 @@ func (s *ConsulSuite) TestNominalConfiguration(c *check.C) { req.Host = "test.localhost" err = try.Request(req, 500*time.Millisecond, - try.StatusCodeIs(200), + try.StatusCodeIs(http.StatusOK), try.BodyContainsOr(whoami3IP, whoami4IP)) c.Assert(err, checker.IsNil) @@ -187,7 +187,7 @@ func (s *ConsulSuite) TestNominalConfiguration(c *check.C) { c.Assert(err, checker.IsNil) err = try.Request(req, 500*time.Millisecond, - try.StatusCodeIs(200), + try.StatusCodeIs(http.StatusOK), try.BodyContainsOr(whoami1IP, whoami2IP)) c.Assert(err, checker.IsNil) diff --git a/integration/docker_test.go b/integration/docker_test.go index 589405502..c6f98eb1f 100644 --- a/integration/docker_test.go +++ b/integration/docker_test.go @@ -87,7 +87,7 @@ func (s *DockerSuite) TestSimpleConfiguration(c *check.C) { // TODO validate : run on 80 // Expected a 404 as we did not comfigure anything - err = try.GetRequest("http://127.0.0.1:8000/", 500*time.Millisecond, try.StatusCodeIs(404)) + err = try.GetRequest("http://127.0.0.1:8000/", 500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) c.Assert(err, checker.IsNil) } @@ -108,7 +108,7 @@ func (s *DockerSuite) TestDefaultDockerContainers(c *check.C) { req.Host = fmt.Sprintf("%s.docker.localhost", strings.Replace(name, "_", "-", -1)) // FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?) - resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, 200) + resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK) c.Assert(err, checker.IsNil) body, err := ioutil.ReadAll(resp.Body) diff --git a/integration/https_test.go b/integration/https_test.go index 38c673bba..d657eca14 100644 --- a/integration/https_test.go +++ b/integration/https_test.go @@ -294,7 +294,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFi func (s *HTTPSSuite) TestWithRootCAsContentForHTTPSOnBackend(c *check.C) { backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) })) defer backend.Close() @@ -316,7 +316,7 @@ func (s *HTTPSSuite) TestWithRootCAsContentForHTTPSOnBackend(c *check.C) { func (s *HTTPSSuite) TestWithRootCAsFileForHTTPSOnBackend(c *check.C) { backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) })) defer backend.Close() diff --git a/integration/websocket_test.go b/integration/websocket_test.go index 125957574..ad58c1ead 100644 --- a/integration/websocket_test.go +++ b/integration/websocket_test.go @@ -365,7 +365,7 @@ func (s *WebsocketSuite) TestBasicAuth(c *check.C) { func (s *WebsocketSuite) TestSpecificResponseFromBackend(c *check.C) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(401) + w.WriteHeader(http.StatusUnauthorized) })) file := s.adaptFile(c, "fixtures/websocket/config.toml", struct { WebsocketServer string @@ -387,7 +387,7 @@ func (s *WebsocketSuite) TestSpecificResponseFromBackend(c *check.C) { _, resp, err := gorillawebsocket.DefaultDialer.Dial("ws://127.0.0.1:8000/ws", nil) c.Assert(err, checker.NotNil) - c.Assert(resp.StatusCode, check.Equals, 401) + c.Assert(resp.StatusCode, check.Equals, http.StatusUnauthorized) } diff --git a/metrics/prometheus.go b/metrics/prometheus.go index 266418f7d..bdf64d4d7 100644 --- a/metrics/prometheus.go +++ b/metrics/prometheus.go @@ -1,6 +1,8 @@ package metrics import ( + "net/http" + "github.com/containous/mux" "github.com/containous/traefik/types" "github.com/go-kit/kit/metrics/prometheus" @@ -21,7 +23,7 @@ type PrometheusHandler struct{} // AddRoutes add Prometheus routes on a router func (h PrometheusHandler) AddRoutes(router *mux.Router) { - router.Methods("GET").Path("/metrics").Handler(promhttp.Handler()) + router.Methods(http.MethodGet).Path("/metrics").Handler(promhttp.Handler()) } // RegisterPrometheus registers all Prometheus metrics. diff --git a/middlewares/accesslog/logger_test.go b/middlewares/accesslog/logger_test.go index 61aa16343..b4ad67927 100644 --- a/middlewares/accesslog/logger_test.go +++ b/middlewares/accesslog/logger_test.go @@ -32,7 +32,7 @@ var ( testPath = "testpath" testPort = 8181 testProto = "HTTP/0.0" - testMethod = "POST" + testMethod = http.MethodPost testReferer = "testReferer" testUserAgent = "testUserAgent" testRetryAttempts = 2 diff --git a/middlewares/error_pages_test.go b/middlewares/error_pages_test.go index 1abadab9b..3c70e0a5d 100644 --- a/middlewares/error_pages_test.go +++ b/middlewares/error_pages_test.go @@ -27,7 +27,7 @@ func TestErrorPage(t *testing.T) { assert.Equal(t, testHandler.BackendURL, ts.URL+"/test", "Should be equal") recorder := httptest.NewRecorder() - req, err := http.NewRequest("GET", ts.URL+"/test", nil) + req, err := http.NewRequest(http.MethodGet, ts.URL+"/test", nil) require.NoError(t, err) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -43,7 +43,7 @@ func TestErrorPage(t *testing.T) { assert.Contains(t, recorder.Body.String(), "traefik") handler500 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, "oops") }) recorder500 := httptest.NewRecorder() @@ -58,7 +58,7 @@ func TestErrorPage(t *testing.T) { assert.NotContains(t, recorder500.Body.String(), "oops", "Should not return the oops page") handler502 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(502) + w.WriteHeader(http.StatusBadGateway) fmt.Fprintln(w, "oops") }) recorder502 := httptest.NewRecorder() @@ -92,13 +92,13 @@ func TestErrorPageQuery(t *testing.T) { assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal") handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(503) + w.WriteHeader(http.StatusServiceUnavailable) fmt.Fprintln(w, "oops") }) recorder := httptest.NewRecorder() - req, err := http.NewRequest("GET", ts.URL+"/test", nil) + req, err := http.NewRequest(http.MethodGet, ts.URL+"/test", nil) require.NoError(t, err) n := negroni.New() @@ -131,13 +131,13 @@ func TestErrorPageSingleCode(t *testing.T) { assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal") handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(503) + w.WriteHeader(http.StatusServiceUnavailable) fmt.Fprintln(w, "oops") }) recorder := httptest.NewRecorder() - req, err := http.NewRequest("GET", ts.URL+"/test", nil) + req, err := http.NewRequest(http.MethodGet, ts.URL+"/test", nil) require.NoError(t, err) n := negroni.New() diff --git a/middlewares/retry.go b/middlewares/retry.go index ce7ab0dbc..94ee99686 100644 --- a/middlewares/retry.go +++ b/middlewares/retry.go @@ -131,7 +131,7 @@ func newRetryResponseRecorder() *retryResponseRecorder { return &retryResponseRecorder{ HeaderMap: make(http.Header), Body: new(bytes.Buffer), - Code: 200, + Code: http.StatusOK, } } diff --git a/middlewares/retry_test.go b/middlewares/retry_test.go index b38163dbe..bb92754a6 100644 --- a/middlewares/retry_test.go +++ b/middlewares/retry_test.go @@ -45,7 +45,7 @@ func TestRetry(t *testing.T) { httpHandler = NewRetry(tc.attempts, httpHandler, tc.listener) recorder := httptest.NewRecorder() - req, err := http.NewRequest("GET", "http://localhost:3000/ok", ioutil.NopCloser(nil)) + req, err := http.NewRequest(http.MethodGet, "http://localhost:3000/ok", ioutil.NopCloser(nil)) if err != nil { t.Fatalf("could not create request: %+v", err) } diff --git a/ping/ping.go b/ping/ping.go index 212415797..6e37052c1 100644 --- a/ping/ping.go +++ b/ping/ping.go @@ -14,7 +14,7 @@ type Handler struct { // AddRoutes add ping routes on a router func (g Handler) AddRoutes(router *mux.Router) { - router.Methods("GET", "HEAD").Path("/ping"). + router.Methods(http.MethodGet, http.MethodHead).Path("/ping"). HandlerFunc(func(response http.ResponseWriter, request *http.Request) { fmt.Fprint(response, "OK") }) diff --git a/provider/rest/rest.go b/provider/rest/rest.go index 65dbe1df9..4d9739d28 100644 --- a/provider/rest/rest.go +++ b/provider/rest/rest.go @@ -24,29 +24,33 @@ var templatesRenderer = render.New(render.Options{Directory: "nowhere"}) // AddRoutes add rest provider routes on a router func (p *Provider) AddRoutes(systemRouter *mux.Router) { - systemRouter.Methods("PUT").Path("/api/providers/{provider}").HandlerFunc(func(response http.ResponseWriter, request *http.Request) { - vars := mux.Vars(request) - // TODO: Deprecated configuration - Need to be removed in the future - if vars["provider"] != "web" && vars["provider"] != "rest" { - response.WriteHeader(http.StatusBadRequest) - fmt.Fprint(response, "Only 'rest' provider can be updated through the REST API") - return - } else if vars["provider"] == "web" { - log.Warn("The provider web is deprecated. Please use /rest instead") - } + systemRouter. + Methods(http.MethodPut). + Path("/api/providers/{provider}"). + HandlerFunc(func(response http.ResponseWriter, request *http.Request) { - configuration := new(types.Configuration) - body, _ := ioutil.ReadAll(request.Body) - err := json.Unmarshal(body, configuration) - if err == nil { - // TODO: Deprecated configuration - Change to `rest` in the future - p.configurationChan <- types.ConfigMessage{ProviderName: "web", Configuration: configuration} - p.getConfigHandler(response, request) - } else { - log.Errorf("Error parsing configuration %+v", err) - http.Error(response, fmt.Sprintf("%+v", err), http.StatusBadRequest) - } - }) + vars := mux.Vars(request) + // TODO: Deprecated configuration - Need to be removed in the future + if vars["provider"] != "web" && vars["provider"] != "rest" { + response.WriteHeader(http.StatusBadRequest) + fmt.Fprint(response, "Only 'rest' provider can be updated through the REST API") + return + } else if vars["provider"] == "web" { + log.Warn("The provider web is deprecated. Please use /rest instead") + } + + configuration := new(types.Configuration) + body, _ := ioutil.ReadAll(request.Body) + err := json.Unmarshal(body, configuration) + if err == nil { + // TODO: Deprecated configuration - Change to `rest` in the future + p.configurationChan <- types.ConfigMessage{ProviderName: "web", Configuration: configuration} + p.getConfigHandler(response, request) + } else { + log.Errorf("Error parsing configuration %+v", err) + http.Error(response, fmt.Sprintf("%+v", err), http.StatusBadRequest) + } + }) } // Provide allows the provider to provide configurations to traefik diff --git a/version/version.go b/version/version.go index 605c10216..61df98b88 100644 --- a/version/version.go +++ b/version/version.go @@ -32,7 +32,7 @@ var ( // AddRoutes add version routes on a router func (v Handler) AddRoutes(router *mux.Router) { - router.Methods("GET").Path("/api/version"). + router.Methods(http.MethodGet).Path("/api/version"). HandlerFunc(func(response http.ResponseWriter, request *http.Request) { v := struct { Version string @@ -63,7 +63,7 @@ func CheckNewVersion() { return } - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { log.Warnf("Error checking new version: status=%s", resp.Status) return }