Use contants from http package.

This commit is contained in:
Ludovic Fernandez 2017-11-20 09:40:03 +01:00 committed by Traefiker
parent 7ed4ae2f8c
commit 05a9350e57
16 changed files with 68 additions and 62 deletions

View file

@ -14,10 +14,10 @@ type DashboardHandler struct{}
// AddRoutes add dashboard routes on a router // AddRoutes add dashboard routes on a router
func (g DashboardHandler) AddRoutes(router *mux.Router) { func (g DashboardHandler) AddRoutes(router *mux.Router) {
// Expose dashboard // 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) 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"}))) Handler(http.StripPrefix("/dashboard/", http.FileServer(&assetfs.AssetFS{Asset: autogen.Asset, AssetInfo: autogen.AssetInfo, AssetDir: autogen.AssetDir, Prefix: "static"})))
} }

View file

@ -22,7 +22,7 @@ type DebugHandler struct{}
// AddRoutes add debug routes on a router // AddRoutes add debug routes on a router
func (g DebugHandler) AddRoutes(router *mux.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) { HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(w, "{\n") fmt.Fprint(w, "{\n")

View file

@ -36,20 +36,20 @@ func (p Handler) AddRoutes(router *mux.Router) {
DebugHandler{}.AddRoutes(router) DebugHandler{}.AddRoutes(router)
} }
router.Methods("GET").Path("/api").HandlerFunc(p.getConfigHandler) router.Methods(http.MethodGet).Path("/api").HandlerFunc(p.getConfigHandler)
router.Methods("GET").Path("/api/providers").HandlerFunc(p.getConfigHandler) router.Methods(http.MethodGet).Path("/api/providers").HandlerFunc(p.getConfigHandler)
router.Methods("GET").Path("/api/providers/{provider}").HandlerFunc(p.getProviderHandler) router.Methods(http.MethodGet).Path("/api/providers/{provider}").HandlerFunc(p.getProviderHandler)
router.Methods("GET").Path("/api/providers/{provider}/backends").HandlerFunc(p.getBackendsHandler) router.Methods(http.MethodGet).Path("/api/providers/{provider}/backends").HandlerFunc(p.getBackendsHandler)
router.Methods("GET").Path("/api/providers/{provider}/backends/{backend}").HandlerFunc(p.getBackendHandler) router.Methods(http.MethodGet).Path("/api/providers/{provider}/backends/{backend}").HandlerFunc(p.getBackendHandler)
router.Methods("GET").Path("/api/providers/{provider}/backends/{backend}/servers").HandlerFunc(p.getServersHandler) router.Methods(http.MethodGet).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(http.MethodGet).Path("/api/providers/{provider}/backends/{backend}/servers/{server}").HandlerFunc(p.getServerHandler)
router.Methods("GET").Path("/api/providers/{provider}/frontends").HandlerFunc(p.getFrontendsHandler) router.Methods(http.MethodGet).Path("/api/providers/{provider}/frontends").HandlerFunc(p.getFrontendsHandler)
router.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}").HandlerFunc(p.getFrontendHandler) router.Methods(http.MethodGet).Path("/api/providers/{provider}/frontends/{frontend}").HandlerFunc(p.getFrontendHandler)
router.Methods("GET").Path("/api/providers/{provider}/frontends/{frontend}/routes").HandlerFunc(p.getRoutesHandler) router.Methods(http.MethodGet).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/providers/{provider}/frontends/{frontend}/routes/{route}").HandlerFunc(p.getRouteHandler)
// health route // health route
router.Methods("GET").Path("/health").HandlerFunc(p.getHealthHandler) router.Methods(http.MethodGet).Path("/health").HandlerFunc(p.getHealthHandler)
version.Handler{}.AddRoutes(router) version.Handler{}.AddRoutes(router)

View file

@ -132,7 +132,7 @@ func checkBackend(currentBackend *BackendHealthCheck) {
func (backend *BackendHealthCheck) newRequest(serverURL *url.URL) (*http.Request, error) { func (backend *BackendHealthCheck) newRequest(serverURL *url.URL) (*http.Request, error) {
if backend.Port == 0 { 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 // 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.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(backend.Port))
u.Path = u.Path + backend.Path 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 { func checkHealth(serverURL *url.URL, backend *BackendHealthCheck) bool {
@ -159,5 +159,5 @@ func checkHealth(serverURL *url.URL, backend *BackendHealthCheck) bool {
if err == nil { if err == nil {
defer resp.Body.Close() defer resp.Body.Close()
} }
return err == nil && resp.StatusCode == 200 return err == nil && resp.StatusCode == http.StatusOK
} }

View file

@ -179,7 +179,7 @@ func (s *ConsulSuite) TestNominalConfiguration(c *check.C) {
req.Host = "test.localhost" req.Host = "test.localhost"
err = try.Request(req, 500*time.Millisecond, err = try.Request(req, 500*time.Millisecond,
try.StatusCodeIs(200), try.StatusCodeIs(http.StatusOK),
try.BodyContainsOr(whoami3IP, whoami4IP)) try.BodyContainsOr(whoami3IP, whoami4IP))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
@ -187,7 +187,7 @@ func (s *ConsulSuite) TestNominalConfiguration(c *check.C) {
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
err = try.Request(req, 500*time.Millisecond, err = try.Request(req, 500*time.Millisecond,
try.StatusCodeIs(200), try.StatusCodeIs(http.StatusOK),
try.BodyContainsOr(whoami1IP, whoami2IP)) try.BodyContainsOr(whoami1IP, whoami2IP))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)

View file

@ -87,7 +87,7 @@ func (s *DockerSuite) TestSimpleConfiguration(c *check.C) {
// TODO validate : run on 80 // TODO validate : run on 80
// Expected a 404 as we did not comfigure anything // 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) 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)) 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 ?) // 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) c.Assert(err, checker.IsNil)
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)

View file

@ -294,7 +294,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFi
func (s *HTTPSSuite) TestWithRootCAsContentForHTTPSOnBackend(c *check.C) { func (s *HTTPSSuite) TestWithRootCAsContentForHTTPSOnBackend(c *check.C) {
backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200) w.WriteHeader(http.StatusOK)
})) }))
defer backend.Close() defer backend.Close()
@ -316,7 +316,7 @@ func (s *HTTPSSuite) TestWithRootCAsContentForHTTPSOnBackend(c *check.C) {
func (s *HTTPSSuite) TestWithRootCAsFileForHTTPSOnBackend(c *check.C) { func (s *HTTPSSuite) TestWithRootCAsFileForHTTPSOnBackend(c *check.C) {
backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200) w.WriteHeader(http.StatusOK)
})) }))
defer backend.Close() defer backend.Close()

View file

@ -365,7 +365,7 @@ func (s *WebsocketSuite) TestBasicAuth(c *check.C) {
func (s *WebsocketSuite) TestSpecificResponseFromBackend(c *check.C) { func (s *WebsocketSuite) TestSpecificResponseFromBackend(c *check.C) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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 { file := s.adaptFile(c, "fixtures/websocket/config.toml", struct {
WebsocketServer string 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) _, resp, err := gorillawebsocket.DefaultDialer.Dial("ws://127.0.0.1:8000/ws", nil)
c.Assert(err, checker.NotNil) c.Assert(err, checker.NotNil)
c.Assert(resp.StatusCode, check.Equals, 401) c.Assert(resp.StatusCode, check.Equals, http.StatusUnauthorized)
} }

View file

@ -1,6 +1,8 @@
package metrics package metrics
import ( import (
"net/http"
"github.com/containous/mux" "github.com/containous/mux"
"github.com/containous/traefik/types" "github.com/containous/traefik/types"
"github.com/go-kit/kit/metrics/prometheus" "github.com/go-kit/kit/metrics/prometheus"
@ -21,7 +23,7 @@ type PrometheusHandler struct{}
// AddRoutes add Prometheus routes on a router // AddRoutes add Prometheus routes on a router
func (h PrometheusHandler) AddRoutes(router *mux.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. // RegisterPrometheus registers all Prometheus metrics.

View file

@ -32,7 +32,7 @@ var (
testPath = "testpath" testPath = "testpath"
testPort = 8181 testPort = 8181
testProto = "HTTP/0.0" testProto = "HTTP/0.0"
testMethod = "POST" testMethod = http.MethodPost
testReferer = "testReferer" testReferer = "testReferer"
testUserAgent = "testUserAgent" testUserAgent = "testUserAgent"
testRetryAttempts = 2 testRetryAttempts = 2

View file

@ -27,7 +27,7 @@ func TestErrorPage(t *testing.T) {
assert.Equal(t, testHandler.BackendURL, ts.URL+"/test", "Should be equal") assert.Equal(t, testHandler.BackendURL, ts.URL+"/test", "Should be equal")
recorder := httptest.NewRecorder() 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) require.NoError(t, err)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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") assert.Contains(t, recorder.Body.String(), "traefik")
handler500 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler500 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500) w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "oops") fmt.Fprintln(w, "oops")
}) })
recorder500 := httptest.NewRecorder() 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") assert.NotContains(t, recorder500.Body.String(), "oops", "Should not return the oops page")
handler502 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler502 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(502) w.WriteHeader(http.StatusBadGateway)
fmt.Fprintln(w, "oops") fmt.Fprintln(w, "oops")
}) })
recorder502 := httptest.NewRecorder() recorder502 := httptest.NewRecorder()
@ -92,13 +92,13 @@ func TestErrorPageQuery(t *testing.T) {
assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal") assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(503) w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, "oops") fmt.Fprintln(w, "oops")
}) })
recorder := httptest.NewRecorder() 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) require.NoError(t, err)
n := negroni.New() n := negroni.New()
@ -131,13 +131,13 @@ func TestErrorPageSingleCode(t *testing.T) {
assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal") assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(503) w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, "oops") fmt.Fprintln(w, "oops")
}) })
recorder := httptest.NewRecorder() 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) require.NoError(t, err)
n := negroni.New() n := negroni.New()

View file

@ -131,7 +131,7 @@ func newRetryResponseRecorder() *retryResponseRecorder {
return &retryResponseRecorder{ return &retryResponseRecorder{
HeaderMap: make(http.Header), HeaderMap: make(http.Header),
Body: new(bytes.Buffer), Body: new(bytes.Buffer),
Code: 200, Code: http.StatusOK,
} }
} }

View file

@ -45,7 +45,7 @@ func TestRetry(t *testing.T) {
httpHandler = NewRetry(tc.attempts, httpHandler, tc.listener) httpHandler = NewRetry(tc.attempts, httpHandler, tc.listener)
recorder := httptest.NewRecorder() 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 { if err != nil {
t.Fatalf("could not create request: %+v", err) t.Fatalf("could not create request: %+v", err)
} }

View file

@ -14,7 +14,7 @@ type Handler struct {
// AddRoutes add ping routes on a router // AddRoutes add ping routes on a router
func (g Handler) AddRoutes(router *mux.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) { HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
fmt.Fprint(response, "OK") fmt.Fprint(response, "OK")
}) })

View file

@ -24,29 +24,33 @@ var templatesRenderer = render.New(render.Options{Directory: "nowhere"})
// AddRoutes add rest provider routes on a router // AddRoutes add rest provider routes on a router
func (p *Provider) AddRoutes(systemRouter *mux.Router) { func (p *Provider) AddRoutes(systemRouter *mux.Router) {
systemRouter.Methods("PUT").Path("/api/providers/{provider}").HandlerFunc(func(response http.ResponseWriter, request *http.Request) { systemRouter.
vars := mux.Vars(request) Methods(http.MethodPut).
// TODO: Deprecated configuration - Need to be removed in the future Path("/api/providers/{provider}").
if vars["provider"] != "web" && vars["provider"] != "rest" { HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
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) vars := mux.Vars(request)
body, _ := ioutil.ReadAll(request.Body) // TODO: Deprecated configuration - Need to be removed in the future
err := json.Unmarshal(body, configuration) if vars["provider"] != "web" && vars["provider"] != "rest" {
if err == nil { response.WriteHeader(http.StatusBadRequest)
// TODO: Deprecated configuration - Change to `rest` in the future fmt.Fprint(response, "Only 'rest' provider can be updated through the REST API")
p.configurationChan <- types.ConfigMessage{ProviderName: "web", Configuration: configuration} return
p.getConfigHandler(response, request) } else if vars["provider"] == "web" {
} else { log.Warn("The provider web is deprecated. Please use /rest instead")
log.Errorf("Error parsing configuration %+v", err) }
http.Error(response, fmt.Sprintf("%+v", err), http.StatusBadRequest)
} 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 // Provide allows the provider to provide configurations to traefik

View file

@ -32,7 +32,7 @@ var (
// AddRoutes add version routes on a router // AddRoutes add version routes on a router
func (v Handler) AddRoutes(router *mux.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) { HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
v := struct { v := struct {
Version string Version string
@ -63,7 +63,7 @@ func CheckNewVersion() {
return return
} }
if resp.StatusCode != 200 { if resp.StatusCode != http.StatusOK {
log.Warnf("Error checking new version: status=%s", resp.Status) log.Warnf("Error checking new version: status=%s", resp.Status)
return return
} }