diff --git a/cmd/kratos/internal/change/get.go b/cmd/kratos/internal/change/get.go index 18e02072a..32046d1ea 100644 --- a/cmd/kratos/internal/change/get.go +++ b/cmd/kratos/internal/change/get.go @@ -43,7 +43,7 @@ func (g *GithubAPI) GetReleaseInfo(version string) ReleaseInfo { if version != "latest" { api = fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/tags/%s", g.Owner, g.Repo, version) } - resp, code := requestGithubAPI(api, "GET", nil, g.Token) + resp, code := requestGithubAPI(api, http.MethodGet, nil, g.Token) if code != http.StatusOK { printGithubErrorInfo(resp) } @@ -63,7 +63,7 @@ func (g *GithubAPI) GetCommitsInfo() []CommitInfo { var list []CommitInfo for { url := fmt.Sprintf("https://api.github.com/repos/%s/%s/commits?pre_page=%d&page=%d&since=%s", g.Owner, g.Repo, prePage, page, info.PublishedAt) - resp, code := requestGithubAPI(url, "GET", nil, g.Token) + resp, code := requestGithubAPI(url, http.MethodGet, nil, g.Token) if code != http.StatusOK { printGithubErrorInfo(resp) } diff --git a/cmd/protoc-gen-go-http/http.go b/cmd/protoc-gen-go-http/http.go index a9eff9a38..1c9298bf7 100644 --- a/cmd/protoc-gen-go-http/http.go +++ b/cmd/protoc-gen-go-http/http.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "net/http" "os" "regexp" "strings" @@ -85,7 +86,7 @@ func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.Generated sd.Methods = append(sd.Methods, buildHTTPRule(g, method, rule)) } else if !omitempty { path := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name()) - sd.Methods = append(sd.Methods, buildMethodDesc(g, method, "POST", path)) + sd.Methods = append(sd.Methods, buildMethodDesc(g, method, http.MethodPost, path)) } } if len(sd.Methods) != 0 { @@ -119,19 +120,19 @@ func buildHTTPRule(g *protogen.GeneratedFile, m *protogen.Method, rule *annotati switch pattern := rule.Pattern.(type) { case *annotations.HttpRule_Get: path = pattern.Get - method = "GET" + method = http.MethodGet case *annotations.HttpRule_Put: path = pattern.Put - method = "PUT" + method = http.MethodPut case *annotations.HttpRule_Post: path = pattern.Post - method = "POST" + method = http.MethodPost case *annotations.HttpRule_Delete: path = pattern.Delete - method = "DELETE" + method = http.MethodDelete case *annotations.HttpRule_Patch: path = pattern.Patch - method = "PATCH" + method = http.MethodPatch case *annotations.HttpRule_Custom: path = pattern.Custom.Path method = pattern.Custom.Kind @@ -139,7 +140,7 @@ func buildHTTPRule(g *protogen.GeneratedFile, m *protogen.Method, rule *annotati body = rule.Body responseBody = rule.ResponseBody md := buildMethodDesc(g, m, method, path) - if method == "GET" || method == "DELETE" { + if method == http.MethodGet || method == http.MethodDelete { if body != "" { _, _ = fmt.Fprintf(os.Stderr, "\u001B[31mWARN\u001B[m: %s %s body should not be declared.\n", method, path) } diff --git a/contrib/opensergo/opensergo.go b/contrib/opensergo/opensergo.go index 112c0babe..e8f38c7bf 100644 --- a/contrib/opensergo/opensergo.go +++ b/contrib/opensergo/opensergo.go @@ -3,6 +3,7 @@ package opensergo import ( "encoding/json" "net" + "net/http" "net/url" "os" "strconv" @@ -186,15 +187,15 @@ func listDescriptors() (services []*v1.ServiceDescriptor, types []*v1.TypeDescri func HTTPPatternInfo(pattern interface{}) (method string, path string) { switch p := pattern.(type) { case *annotations.HttpRule_Get: - return "GET", p.Get + return http.MethodGet, p.Get case *annotations.HttpRule_Post: - return "POST", p.Post + return http.MethodPost, p.Post case *annotations.HttpRule_Delete: - return "DELETE", p.Delete + return http.MethodDelete, p.Delete case *annotations.HttpRule_Patch: - return "PATCH", p.Patch + return http.MethodPatch, p.Patch case *annotations.HttpRule_Put: - return "PUT", p.Put + return http.MethodPut, p.Put case *annotations.HttpRule_Custom: return p.Custom.Kind, p.Custom.Path default: diff --git a/contrib/opensergo/opensergo_test.go b/contrib/opensergo/opensergo_test.go index b63430e20..70ffef8fc 100644 --- a/contrib/opensergo/opensergo_test.go +++ b/contrib/opensergo/opensergo_test.go @@ -2,6 +2,7 @@ package opensergo import ( "net" + "net/http" "os" "path/filepath" "reflect" @@ -195,7 +196,7 @@ func TestHTTPPatternInfo(t *testing.T) { args: args{ pattern: &annotations.HttpRule_Get{Get: "/foo"}, }, - wantMethod: "GET", + wantMethod: http.MethodGet, wantPath: "/foo", }, { @@ -203,7 +204,7 @@ func TestHTTPPatternInfo(t *testing.T) { args: args{ pattern: &annotations.HttpRule_Post{Post: "/foo"}, }, - wantMethod: "POST", + wantMethod: http.MethodPost, wantPath: "/foo", }, { @@ -211,7 +212,7 @@ func TestHTTPPatternInfo(t *testing.T) { args: args{ pattern: &annotations.HttpRule_Put{Put: "/foo"}, }, - wantMethod: "PUT", + wantMethod: http.MethodPut, wantPath: "/foo", }, { @@ -219,7 +220,7 @@ func TestHTTPPatternInfo(t *testing.T) { args: args{ pattern: &annotations.HttpRule_Delete{Delete: "/foo"}, }, - wantMethod: "DELETE", + wantMethod: http.MethodDelete, wantPath: "/foo", }, { @@ -227,7 +228,7 @@ func TestHTTPPatternInfo(t *testing.T) { args: args{ pattern: &annotations.HttpRule_Patch{Patch: "/foo"}, }, - wantMethod: "PATCH", + wantMethod: http.MethodPatch, wantPath: "/foo", }, { diff --git a/contrib/registry/eureka/client.go b/contrib/registry/eureka/client.go index 020a9a904..ab9eb30d2 100644 --- a/contrib/registry/eureka/client.go +++ b/contrib/registry/eureka/client.go @@ -153,7 +153,7 @@ func NewClient(urls []string, opts ...ClientOption) *Client { func (e *Client) FetchApps(ctx context.Context) []Application { var m ApplicationsRootResponse - if err := e.do(ctx, "GET", []string{"apps"}, nil, &m); err != nil { + if err := e.do(ctx, http.MethodGet, []string{"apps"}, nil, &m); err != nil { return nil } @@ -161,7 +161,7 @@ func (e *Client) FetchApps(ctx context.Context) []Application { } func (e *Client) FetchAppInstances(ctx context.Context, appID string) (m Application, err error) { - err = e.do(ctx, "GET", []string{"apps", appID}, nil, &m) + err = e.do(ctx, http.MethodGet, []string{"apps", appID}, nil, &m) return } @@ -174,21 +174,21 @@ func (e *Client) FetchAppUpInstances(ctx context.Context, appID string) []Instan } func (e *Client) FetchAppInstance(ctx context.Context, appID string, instanceID string) (m Instance, err error) { - err = e.do(ctx, "GET", []string{"apps", appID, instanceID}, nil, &m) + err = e.do(ctx, http.MethodGet, []string{"apps", appID, instanceID}, nil, &m) return } func (e *Client) FetchInstance(ctx context.Context, instanceID string) (m Instance, err error) { - err = e.do(ctx, "GET", []string{"instances", instanceID}, nil, &m) + err = e.do(ctx, http.MethodGet, []string{"instances", instanceID}, nil, &m) return } func (e *Client) Out(ctx context.Context, appID, instanceID string) error { - return e.do(ctx, "PUT", []string{"apps", appID, instanceID, fmt.Sprintf("status?value=%s", statusOutOfService)}, nil, nil) + return e.do(ctx, http.MethodPut, []string{"apps", appID, instanceID, fmt.Sprintf("status?value=%s", statusOutOfService)}, nil, nil) } func (e *Client) Down(ctx context.Context, appID, instanceID string) error { - return e.do(ctx, "PUT", []string{"apps", appID, instanceID, fmt.Sprintf("status?value=%s", statusDown)}, nil, nil) + return e.do(ctx, http.MethodPut, []string{"apps", appID, instanceID, fmt.Sprintf("status?value=%s", statusDown)}, nil, nil) } func (e *Client) FetchAllUpInstances(ctx context.Context) []Instance { @@ -200,7 +200,7 @@ func (e *Client) Register(ctx context.Context, ep Endpoint) error { } func (e *Client) Deregister(ctx context.Context, appID, instanceID string) error { - if err := e.do(ctx, "DELETE", []string{"apps", appID, instanceID}, nil, nil); err != nil { + if err := e.do(ctx, http.MethodDelete, []string{"apps", appID, instanceID}, nil, nil); err != nil { return err } go e.cancelHeartbeat(appID) @@ -239,7 +239,7 @@ func (e *Client) registerEndpoint(ctx context.Context, ep Endpoint) error { if err != nil { return err } - return e.do(ctx, "POST", []string{"apps", ep.AppID}, bytes.NewReader(body), nil) + return e.do(ctx, http.MethodPost, []string{"apps", ep.AppID}, bytes.NewReader(body), nil) } func (e *Client) Heartbeat(ep Endpoint) { @@ -257,7 +257,7 @@ func (e *Client) Heartbeat(ep Endpoint) { case <-e.keepalive[ep.AppID]: return case <-ticker.C: - if err := e.do(e.ctx, "PUT", []string{"apps", ep.AppID, ep.InstanceID}, nil, nil); err != nil { + if err := e.do(e.ctx, http.MethodPut, []string{"apps", ep.AppID, ep.InstanceID}, nil, nil); err != nil { if retryCount++; retryCount > heartbeatRetry { _ = e.registerEndpoint(e.ctx, ep) retryCount = 0 diff --git a/transport/http/binding/bind_test.go b/transport/http/binding/bind_test.go index 20aadba7f..6cd8b6d5a 100644 --- a/transport/http/binding/bind_test.go +++ b/transport/http/binding/bind_test.go @@ -96,7 +96,7 @@ func TestBindForm(t *testing.T) { { name: "error not nil", args: args{ - req: &http.Request{Method: "POST"}, + req: &http.Request{Method: http.MethodPost}, target: &p1, }, wantErr: true, @@ -106,7 +106,7 @@ func TestBindForm(t *testing.T) { name: "error is nil", args: args{ req: &http.Request{ - Method: "POST", + Method: http.MethodPost, Header: http.Header{"Content-Type": {"application/x-www-form-urlencoded; param=value"}}, Body: io.NopCloser(strings.NewReader("name=kratos&url=https://go-kratos.dev/")), }, @@ -119,7 +119,7 @@ func TestBindForm(t *testing.T) { name: "error BadRequest", args: args{ req: &http.Request{ - Method: "POST", + Method: http.MethodPost, Header: http.Header{"Content-Type": {"application/x-www-form-urlencoded; param=value"}}, Body: io.NopCloser(strings.NewReader("age=a")), }, diff --git a/transport/http/client_test.go b/transport/http/client_test.go index ab8031dd5..9a0dd7829 100644 --- a/transport/http/client_test.go +++ b/transport/http/client_test.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "log" + "net/http" nethttp "net/http" "reflect" "strconv" @@ -348,18 +349,18 @@ func TestNewClient(t *testing.T) { t.Error(err) } - err = client.Invoke(context.Background(), "POST", "/go", map[string]string{"name": "kratos"}, nil, EmptyCallOption{}, &mockCallOption{}) + err = client.Invoke(context.Background(), http.MethodPost, "/go", map[string]string{"name": "kratos"}, nil, EmptyCallOption{}, &mockCallOption{}) if err == nil { t.Error("err should not be equal to nil") } - err = client.Invoke(context.Background(), "POST", "/go", map[string]string{"name": "kratos"}, nil, EmptyCallOption{}, &mockCallOption{needErr: true}) + err = client.Invoke(context.Background(), http.MethodPost, "/go", map[string]string{"name": "kratos"}, nil, EmptyCallOption{}, &mockCallOption{needErr: true}) if err == nil { t.Error("err should be equal to callOption err") } client.opts.encoder = func(ctx context.Context, contentType string, in interface{}) (body []byte, err error) { return nil, errors.New("mock test encoder error") } - err = client.Invoke(context.Background(), "POST", "/go", map[string]string{"name": "kratos"}, nil, EmptyCallOption{}) + err = client.Invoke(context.Background(), http.MethodPost, "/go", map[string]string{"name": "kratos"}, nil, EmptyCallOption{}) if err == nil { t.Error("err should be equal to encoder error") } diff --git a/transport/http/context_test.go b/transport/http/context_test.go index daccccd95..6cae1b9ad 100644 --- a/transport/http/context_test.go +++ b/transport/http/context_test.go @@ -30,7 +30,7 @@ func TestContextHeader(t *testing.T) { func TestContextForm(t *testing.T) { w := wrapper{ router: testRouter, - req: &http.Request{Header: map[string][]string{"name": {"kratos"}}, Method: "POST"}, + req: &http.Request{Header: map[string][]string{"name": {"kratos"}}, Method: http.MethodPost}, res: nil, w: responseWriter{}, } @@ -54,7 +54,7 @@ func TestContextForm(t *testing.T) { func TestContextQuery(t *testing.T) { w := wrapper{ router: testRouter, - req: &http.Request{URL: &url.URL{Scheme: "https", Host: "github.com", Path: "go-kratos/kratos", RawQuery: "page=1"}, Method: "POST"}, + req: &http.Request{URL: &url.URL{Scheme: "https", Host: "github.com", Path: "go-kratos/kratos", RawQuery: "page=1"}, Method: http.MethodPost}, res: nil, w: responseWriter{}, } @@ -65,7 +65,7 @@ func TestContextQuery(t *testing.T) { } func TestContextRequest(t *testing.T) { - req := &http.Request{Method: "POST"} + req := &http.Request{Method: http.MethodPost} w := wrapper{ router: testRouter, req: req, @@ -82,7 +82,7 @@ func TestContextResponse(t *testing.T) { res := httptest.NewRecorder() w := wrapper{ router: &Router{srv: &Server{enc: DefaultResponseEncoder}}, - req: &http.Request{Method: "POST"}, + req: &http.Request{Method: http.MethodPost}, res: res, w: responseWriter{200, res}, } @@ -173,7 +173,7 @@ func TestContextResponseReturn(t *testing.T) { func TestContextCtx(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - req := &http.Request{Method: "POST"} + req := &http.Request{Method: http.MethodPost} req = req.WithContext(ctx) w := wrapper{ router: testRouter, diff --git a/transport/http/redirect_test.go b/transport/http/redirect_test.go index b98bf4f0b..879966a4b 100644 --- a/transport/http/redirect_test.go +++ b/transport/http/redirect_test.go @@ -1,6 +1,7 @@ package http import ( + "net/http" "net/http/httptest" "testing" ) @@ -10,7 +11,7 @@ func TestRedirect(t *testing.T) { redirectURL = "/redirect" redirectCode = 302 ) - r := httptest.NewRequest("POST", "/test", nil) + r := httptest.NewRequest(http.MethodPost, "/test", nil) w := httptest.NewRecorder() _ = DefaultResponseEncoder(w, r, NewRedirect(redirectURL, redirectCode)) diff --git a/transport/http/router_test.go b/transport/http/router_test.go index ad37831d1..747ebf059 100644 --- a/transport/http/router_test.go +++ b/transport/http/router_test.go @@ -136,7 +136,7 @@ func testRoute(t *testing.T, srv *Server) { t.Fatalf("got %s want bar", u.Name) } // PUT - req, _ := http.NewRequest("PUT", base+"/users", strings.NewReader(`{"name":"bar"}`)) + req, _ := http.NewRequest(http.MethodPut, base+"/users", strings.NewReader(`{"name":"bar"}`)) req.Header.Set("Content-Type", appJSONStr) resp, err = http.DefaultClient.Do(req) if err != nil { @@ -157,7 +157,7 @@ func testRoute(t *testing.T, srv *Server) { t.Fatalf("got %s want bar", u.Name) } // OPTIONS - req, _ = http.NewRequest("OPTIONS", base+"/users", nil) + req, _ = http.NewRequest(http.MethodOptions, base+"/users", nil) resp, err = http.DefaultClient.Do(req) if err != nil { t.Fatal(err) @@ -166,7 +166,7 @@ func testRoute(t *testing.T, srv *Server) { if resp.StatusCode != 200 { t.Fatalf("code: %d", resp.StatusCode) } - if resp.Header.Get("Access-Control-Allow-Methods") != "OPTIONS" { + if resp.Header.Get("Access-Control-Allow-Methods") != http.MethodOptions { t.Fatal("cors failed") } } diff --git a/transport/http/server_test.go b/transport/http/server_test.go index ff9b3918c..22865fc33 100644 --- a/transport/http/server_test.go +++ b/transport/http/server_test.go @@ -117,8 +117,8 @@ func testAccept(t *testing.T, srv *Server) { path string contentType string }{ - {"GET", "/errors/cause", "application/json"}, - {"GET", "/errors/cause", "application/proto"}, + {http.MethodGet, "/errors/cause", "application/json"}, + {http.MethodGet, "/errors/cause", "application/proto"}, } e, err := srv.Endpoint() if err != nil { @@ -154,7 +154,7 @@ func testHeader(t *testing.T, srv *Server) { t.Errorf("expected nil got %v", err) } reqURL := fmt.Sprintf(e.String() + "/index") - req, err := http.NewRequest("GET", reqURL, nil) + req, err := http.NewRequest(http.MethodGet, reqURL, nil) if err != nil { t.Errorf("expected nil got %v", err) } @@ -172,21 +172,21 @@ func testClient(t *testing.T, srv *Server) { path string code int }{ - {"GET", "/index", http.StatusOK}, - {"PUT", "/index", http.StatusOK}, - {"POST", "/index", http.StatusOK}, - {"PATCH", "/index", http.StatusOK}, - {"DELETE", "/index", http.StatusOK}, + {http.MethodGet, "/index", http.StatusOK}, + {http.MethodPut, "/index", http.StatusOK}, + {http.MethodPost, "/index", http.StatusOK}, + {http.MethodPatch, "/index", http.StatusOK}, + {http.MethodDelete, "/index", http.StatusOK}, - {"GET", "/index/1", http.StatusOK}, - {"PUT", "/index/1", http.StatusOK}, - {"POST", "/index/1", http.StatusOK}, - {"PATCH", "/index/1", http.StatusOK}, - {"DELETE", "/index/1", http.StatusOK}, + {http.MethodGet, "/index/1", http.StatusOK}, + {http.MethodPut, "/index/1", http.StatusOK}, + {http.MethodPost, "/index/1", http.StatusOK}, + {http.MethodPatch, "/index/1", http.StatusOK}, + {http.MethodDelete, "/index/1", http.StatusOK}, - {"GET", "/index/notfound", http.StatusNotFound}, - {"GET", "/errors/cause", http.StatusBadRequest}, - {"GET", "/test/prefix/123111", http.StatusOK}, + {http.MethodGet, "/index/notfound", http.StatusNotFound}, + {http.MethodGet, "/errors/cause", http.StatusBadRequest}, + {http.MethodGet, "/test/prefix/123111", http.StatusOK}, } e, err := srv.Endpoint() if err != nil { @@ -273,7 +273,7 @@ func BenchmarkServer(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { var res testData - err := client.Invoke(context.Background(), "POST", "/index", nil, &res) + err := client.Invoke(context.Background(), http.MethodPost, "/index", nil, &res) if err != nil { b.Errorf("expected nil got %v", err) }