Skip to content

Commit 8fbd967

Browse files
committed
添加auther
1 parent 1a72e38 commit 8fbd967

File tree

10 files changed

+109
-90
lines changed

10 files changed

+109
-90
lines changed

http/auth/mock/mock.go renamed to http/mock/auth.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import (
55
"strings"
66

77
"github.com/infraboard/mcube/exception"
8-
"github.com/infraboard/mcube/http/auth"
8+
"github.com/infraboard/mcube/http/router"
99
)
1010

1111
var (
@@ -14,7 +14,7 @@ var (
1414
)
1515

1616
// NewMockAuther mock
17-
func NewMockAuther() auth.Auther {
17+
func NewMockAuther() router.Auther {
1818
return &mockAuther{}
1919
}
2020

http/auth/auther_test.go renamed to http/router/auth_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
package auth_test
1+
package router_test
22

33
import (
44
"net/http"
55
"testing"
66

7-
"github.com/infraboard/mcube/http/auth"
7+
"github.com/infraboard/mcube/http/router"
88
"github.com/stretchr/testify/require"
99
)
1010

@@ -16,7 +16,7 @@ func simpleAuth(h http.Header) (authInfo interface{}, err error) {
1616
func TestAutherFunc(t *testing.T) {
1717
should := require.New(t)
1818

19-
auther := auth.AutherFunc(simpleAuth)
19+
auther := router.AutherFunc(simpleAuth)
2020
header := make(http.Header)
2121
header.Add("Authorization", "ok")
2222
authInfo, err := auther.Auth(header)

http/auth/auther.go renamed to http/router/auther.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package auth
1+
package router
22

33
import "net/http"
44

http/router/entry.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package router
2+
3+
// Entry 路由条目
4+
type Entry struct {
5+
Name string `json:"name,omitempty"`
6+
Resource string `json:"resource,omitempty"`
7+
Path string `json:"path,omitempty"`
8+
Method string `json:"method,omitempty"`
9+
Protected bool `json:"protected"`
10+
Labels map[string]string `json:"labels,omitempty"`
11+
}
12+
13+
// NewEntrySet 实例化一个集合
14+
func NewEntrySet() *EntrySet {
15+
return &EntrySet{}
16+
}
17+
18+
// EntrySet 路由集合
19+
type EntrySet struct {
20+
items []Entry
21+
}
22+
23+
// AddEntry 添加理由条目
24+
func (s *EntrySet) AddEntry(e ...Entry) {
25+
s.items = append(s.items, e...)
26+
}
27+
28+
// ShowEntries 显示理由条目
29+
func (s *EntrySet) ShowEntries() []Entry {
30+
return s.items
31+
}

http/router/httprouter/httprouter.go

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"log"
55
"net/http"
66

7-
"github.com/infraboard/mcube/http/auth"
87
"github.com/infraboard/mcube/http/context"
98
"github.com/infraboard/mcube/http/response"
109
"github.com/infraboard/mcube/http/router"
@@ -26,7 +25,7 @@ type httpRouter struct {
2625

2726
middlewareChain []router.Middleware
2827
entries []*entry
29-
authMiddleware router.Middleware
28+
auther router.Auther
3029
mergedHandler http.Handler
3130
labels []*router.Label
3231
}
@@ -80,9 +79,8 @@ func (r *httpRouter) AddPublict(method, path string, h http.HandlerFunc) {
8079
r.add(e)
8180
}
8281

83-
func (r *httpRouter) SetAuther(at auth.Auther) {
84-
am := router.NewAutherMiddleware(at)
85-
r.authMiddleware = am
82+
func (r *httpRouter) SetAuther(at router.Auther) {
83+
r.auther = at
8684
return
8785
}
8886

@@ -105,13 +103,14 @@ func (r *httpRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
105103
r.r.ServeHTTP(response.NewResponse(w), req)
106104
}
107105

108-
func (r *httpRouter) GetEndpoints() []router.Entry {
109-
entries := make([]router.Entry, 0, len(r.entries))
106+
func (r *httpRouter) GetEndpoints() *router.EntrySet {
107+
es := router.NewEntrySet()
108+
110109
for i := range r.entries {
111-
entries = append(entries, r.entries[i].Entry)
110+
es.AddEntry(r.entries[i].Entry)
112111
}
113112

114-
return entries
113+
return es
115114
}
116115

117116
func (r *httpRouter) EnableAPIRoot() {
@@ -139,29 +138,42 @@ func (r *httpRouter) debug(format string, args ...interface{}) {
139138
func (r *httpRouter) add(e *entry) {
140139
var handler http.Handler
141140

142-
if e.Protected && r.authMiddleware == nil {
141+
if e.Protected && r.auther == nil {
143142
r.debug("add projected endpoint, but no auther set")
144143
}
145144

146-
if e.Protected && r.authMiddleware != nil {
147-
handler = r.authMiddleware.Handler(e.h)
148-
} else {
149-
handler = http.HandlerFunc(e.h)
150-
}
145+
handler = http.HandlerFunc(e.h)
151146

152-
r.addHandler(e.Method, e.Path, handler)
147+
r.addHandler(e.Protected, e.Method, e.Path, handler)
153148
r.addEntry(e)
154149
}
155150

156-
func (r *httpRouter) addHandler(method, path string, h http.Handler) {
151+
func (r *httpRouter) addHandler(protected bool, method, path string, h http.Handler) {
157152
r.r.Handle(method, path,
158153
func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
159-
rc := &context.ReqContext{
160-
PS: ps,
154+
// 使用auther进行认证
155+
if protected && r.auther != nil {
156+
authInfo, err := r.auther.Auth(req.Header)
157+
if err != nil {
158+
response.Failed(w, err)
159+
return
160+
}
161+
162+
rc := context.GetContext(req)
163+
rc.AuthInfo = authInfo
164+
req = context.WithContext(req, rc)
161165
}
162-
req = context.WithContext(req, rc)
163-
h.ServeHTTP(w, req)
164166

167+
// 未包含和auth为nil
168+
if !protected || r.auther == nil {
169+
rc := &context.ReqContext{
170+
PS: ps,
171+
}
172+
173+
req = context.WithContext(req, rc)
174+
}
175+
176+
h.ServeHTTP(w, req)
165177
},
166178
)
167179
}

http/router/httprouter/httprouter_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"testing"
77

88
"github.com/infraboard/mcube/exception"
9-
"github.com/infraboard/mcube/http/auth/mock"
9+
"github.com/infraboard/mcube/http/mock"
1010
"github.com/infraboard/mcube/http/context"
1111
"github.com/infraboard/mcube/http/response"
1212
"github.com/infraboard/mcube/http/router"
@@ -80,7 +80,7 @@ func TestWithAutherOK(t *testing.T) {
8080
r.AddProtected("GET", "/", IndexHandler)
8181
r.ServeHTTP(w, req)
8282

83-
should.Equal(w.Code, 200)
83+
should.Equal(200, w.Code)
8484
}
8585

8686
func TestWithParamsOK(t *testing.T) {
@@ -94,7 +94,7 @@ func TestWithParamsOK(t *testing.T) {
9494
r.AddProtected("GET", "/:id", WithContextHandler)
9595
r.ServeHTTP(w, req)
9696

97-
should.Equal(w.Code, 200)
97+
should.Equal(200, w.Code)
9898
}
9999

100100
func TestWithParamsFailed(t *testing.T) {
@@ -108,7 +108,7 @@ func TestWithParamsFailed(t *testing.T) {
108108
r.AddProtected("GET", "/:id", WithContextHandler)
109109
r.ServeHTTP(w, req)
110110

111-
should.Equal(w.Code, 400)
111+
should.Equal(400, w.Code)
112112
}
113113

114114
func TestSetLabel(t *testing.T) {
@@ -118,7 +118,7 @@ func TestSetLabel(t *testing.T) {
118118
r.SetLabel(router.NewLable("k1", "v1"))
119119
r.AddProtected("GET", "/:id", WithContextHandler)
120120

121-
entries := r.GetEndpoints()
121+
entries := r.GetEndpoints().ShowEntries()
122122

123123
should.Equal(entries[0].Labels["k1"], "v1")
124124
}

http/router/httprouter/subrouter.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ func newSubRouter(basePath string, root *httpRouter) *subRouter {
1616

1717
type subRouter struct {
1818
basePath string
19+
resourceName string
1920
root *httpRouter
2021
labels []*router.Label
2122
middlewareChain []router.Middleware
@@ -56,10 +57,11 @@ func (r *subRouter) AddProtected(method, path string, h http.HandlerFunc) {
5657
func (r *subRouter) AddPublict(method, path string, h http.HandlerFunc) {
5758
e := &entry{
5859
Entry: router.Entry{
59-
Name: router.GetHandlerFuncName(h),
60-
Method: method,
61-
Path: path,
62-
Labels: map[string]string{},
60+
Resource: r.resourceName,
61+
Name: router.GetHandlerFuncName(h),
62+
Method: method,
63+
Path: path,
64+
Labels: map[string]string{},
6365
},
6466
needAuth: false,
6567
h: h,
@@ -72,6 +74,14 @@ func (r *subRouter) SetLabel(labels ...*router.Label) {
7274
r.labels = append(r.labels, labels...)
7375
}
7476

77+
func (r *subRouter) ResourceRouter(resourceName string) router.SubRouter {
78+
return &subRouter{
79+
resourceName: resourceName,
80+
basePath: r.basePath + "/" + resourceName,
81+
root: r.root,
82+
}
83+
}
84+
7585
func (r *subRouter) add(e *entry) {
7686
// 子路由全局标签
7787
for i := range r.labels {
@@ -81,7 +91,7 @@ func (r *subRouter) add(e *entry) {
8191

8292
mergedHandler := r.combineHandler(e)
8393
e.Path = r.calculateAbsolutePath(e.Path)
84-
r.root.addHandler(e.Method, e.Path, mergedHandler)
94+
r.root.addHandler(e.Protected, e.Method, e.Path, mergedHandler)
8595
r.root.addEntry(e)
8696
}
8797

http/router/httprouter/subrouter_test.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ func TestSubRouterTestSuit(t *testing.T) {
1717

1818
t.Run("SetLabel", suit.testSetLabel())
1919
t.Run("AddPublictOK", suit.testAddPublictOK())
20+
t.Run("ResourceRouterOK", suit.testResourceRouterOK())
2021
}
2122

2223
func newSubRouterTestSuit(t *testing.T) *subRouterTestSuit {
@@ -45,7 +46,7 @@ func (a *subRouterTestSuit) testSetLabel() func(t *testing.T) {
4546
a.sub.SetLabel(router.NewLable("k1", "v1"))
4647
a.sub.AddPublict("GET", "/index", IndexHandler)
4748

48-
entries := a.root.GetEndpoints()
49+
entries := a.root.GetEndpoints().ShowEntries()
4950

5051
a.should.Equal(entries[0].Labels["k1"], "v1")
5152
}
@@ -65,3 +66,15 @@ func (a *subRouterTestSuit) testAddPublictOK() func(t *testing.T) {
6566
a.should.Equal(w.Code, 200)
6667
}
6768
}
69+
70+
func (a *subRouterTestSuit) testResourceRouterOK() func(t *testing.T) {
71+
return func(t *testing.T) {
72+
a.sub.ResourceRouter("resources").AddPublict("GET", "/", IndexHandler)
73+
74+
w := httptest.NewRecorder()
75+
req, _ := http.NewRequest("GET", "/v1/resources/", nil)
76+
a.root.ServeHTTP(w, req)
77+
78+
a.should.Equal(w.Code, 200)
79+
}
80+
}

http/router/middleware.go

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,6 @@ package router
22

33
import (
44
"net/http"
5-
6-
"github.com/infraboard/mcube/http/auth"
7-
"github.com/infraboard/mcube/http/context"
8-
"github.com/infraboard/mcube/http/response"
95
)
106

117
// Middleware 中间件的函数签名
@@ -21,34 +17,3 @@ type MiddlewareFunc func(http.Handler) http.Handler
2117
func (h MiddlewareFunc) Handler(next http.Handler) http.Handler {
2218
return h(next)
2319
}
24-
25-
// NewAutherMiddleware 初始化一个认证中间件
26-
func NewAutherMiddleware(auther auth.Auther) Middleware {
27-
return &AutherMiddleware{
28-
auther: auther,
29-
}
30-
}
31-
32-
// AutherMiddleware 认证中间件
33-
type AutherMiddleware struct {
34-
auther auth.Auther
35-
}
36-
37-
// Handler 实现中间件
38-
func (m *AutherMiddleware) Handler(next http.Handler) http.Handler {
39-
return http.HandlerFunc(func(wr http.ResponseWriter, r *http.Request) {
40-
// 使用auther进行认证
41-
authInfo, err := m.auther.Auth(r.Header)
42-
if err != nil {
43-
response.Failed(wr, err)
44-
return
45-
}
46-
47-
rc := context.GetContext(r)
48-
rc.AuthInfo = authInfo
49-
context.WithContext(r, rc)
50-
51-
// next handler
52-
next.ServeHTTP(wr, r)
53-
})
54-
}

0 commit comments

Comments
 (0)