Selaa lähdekoodia

feat: add rest.WithPrefix to support route prefix (#1194)

Kevin Wan 3 vuotta sitten
vanhempi
sitoutus
91b10bd3b9
2 muutettua tiedostoa jossa 36 lisäystä ja 0 poistoa
  1. 17 0
      rest/server.go
  2. 19 0
      rest/server_test.go

+ 17 - 0
rest/server.go

@@ -4,6 +4,7 @@ import (
 	"crypto/tls"
 	"crypto/tls"
 	"log"
 	"log"
 	"net/http"
 	"net/http"
+	"path"
 
 
 	"github.com/tal-tech/go-zero/core/logx"
 	"github.com/tal-tech/go-zero/core/logx"
 	"github.com/tal-tech/go-zero/rest/handler"
 	"github.com/tal-tech/go-zero/rest/handler"
@@ -161,6 +162,22 @@ func WithNotAllowedHandler(handler http.Handler) RunOption {
 	return WithRouter(rt)
 	return WithRouter(rt)
 }
 }
 
 
+// WithPrefix adds group as a prefix to the route paths.
+func WithPrefix(group string) RouteOption {
+	return func(r *featuredRoutes) {
+		var routes []Route
+		for _, rt := range r.routes {
+			p := path.Join(group, rt.Path)
+			routes = append(routes, Route{
+				Method:  rt.Method,
+				Path:    p,
+				Handler: rt.Handler,
+			})
+		}
+		r.routes = routes
+	}
+}
+
 // WithPriority returns a RunOption with priority.
 // WithPriority returns a RunOption with priority.
 func WithPriority() RouteOption {
 func WithPriority() RouteOption {
 	return func(r *featuredRoutes) {
 	return func(r *featuredRoutes) {

+ 19 - 0
rest/server_test.go

@@ -213,6 +213,25 @@ func TestMultiMiddlewares(t *testing.T) {
 	}, m)
 	}, m)
 }
 }
 
 
+func TestWithPrefix(t *testing.T) {
+	fr := featuredRoutes{
+		routes: []Route{
+			{
+				Path: "/hello",
+			},
+			{
+				Path: "/world",
+			},
+		},
+	}
+	WithPrefix("/api")(&fr)
+	var vals []string
+	for _, r := range fr.routes {
+		vals = append(vals, r.Path)
+	}
+	assert.EqualValues(t, []string{"/api/hello", "/api/world"}, vals)
+}
+
 func TestWithPriority(t *testing.T) {
 func TestWithPriority(t *testing.T) {
 	var fr featuredRoutes
 	var fr featuredRoutes
 	WithPriority()(&fr)
 	WithPriority()(&fr)