style(transport): remove duplicate get path code (#1188)

transport/http remove duplicate get path code for filter
pull/1190/head
opensite 3 years ago committed by GitHub
parent e8c9a361d3
commit f27047c05b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      transport/http/server.go
  2. 22
      transport/http/server_test.go

@ -174,11 +174,6 @@ func (s *Server) filter() mux.MiddlewareFunc {
request: req, request: req,
pathTemplate: pathTemplate, pathTemplate: pathTemplate,
} }
if r := mux.CurrentRoute(req); r != nil {
if path, err := r.GetPathTemplate(); err == nil {
tr.operation = path
}
}
ctx = transport.NewServerContext(ctx, tr) ctx = transport.NewServerContext(ctx, tr)
next.ServeHTTP(w, req.WithContext(ctx)) next.ServeHTTP(w, req.WithContext(ctx))
}) })

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/go-kratos/kratos/v2/errors"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
@ -27,6 +28,7 @@ func TestServer(t *testing.T) {
ctx := context.Background() ctx := context.Background()
srv := NewServer() srv := NewServer()
srv.HandleFunc("/index", fn) srv.HandleFunc("/index", fn)
srv.HandleFunc("/index/{id:[0-9]+}", fn)
if e, err := srv.Endpoint(); err != nil || e == nil || strings.HasSuffix(e.Host, ":0") { if e, err := srv.Endpoint(); err != nil || e == nil || strings.HasSuffix(e.Host, ":0") {
t.Fatal(e, err) t.Fatal(e, err)
@ -52,6 +54,14 @@ func testClient(t *testing.T, srv *Server) {
{"POST", "/index"}, {"POST", "/index"},
{"PATCH", "/index"}, {"PATCH", "/index"},
{"DELETE", "/index"}, {"DELETE", "/index"},
{"GET", "/index/1"},
{"PUT", "/index/1"},
{"POST", "/index/1"},
{"PATCH", "/index/1"},
{"DELETE", "/index/1"},
{"GET", "/index/notfound"},
} }
e, err := srv.Endpoint() e, err := srv.Endpoint()
if err != nil { if err != nil {
@ -69,6 +79,13 @@ func testClient(t *testing.T, srv *Server) {
t.Fatal(err) t.Fatal(err)
} }
resp, err := client.Do(req) resp, err := client.Do(req)
if test.path == "/index/notfound" && err != nil {
if e, ok := err.(*errors.Error); ok && e.Code == http.StatusNotFound {
continue
}
}
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -90,6 +107,11 @@ func testClient(t *testing.T, srv *Server) {
for _, test := range tests { for _, test := range tests {
var res testData var res testData
err := client.Invoke(context.Background(), test.method, test.path, nil, &res) err := client.Invoke(context.Background(), test.method, test.path, nil, &res)
if test.path == "/index/notfound" && err != nil {
if e, ok := err.(*errors.Error); ok && e.Code == http.StatusNotFound {
continue
}
}
if err != nil { if err != nil {
t.Fatalf("invoke error %v", err) t.Fatalf("invoke error %v", err)
} }

Loading…
Cancel
Save