Skip to content

Commit 067898e

Browse files
committed
http模块修改完成
1 parent 43df0be commit 067898e

File tree

3 files changed

+23
-10
lines changed

3 files changed

+23
-10
lines changed

http/server/handler.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,22 @@ func NameToPath(name string, depth int) string {
6464
return string(buf[index:])
6565
}
6666

67-
//AddInterface 自动注册接口
68-
//只要struct实现了Get(),Post(),Delete(),Put()接口就可以自动注册
69-
func AddInterface(obj interface{}, path string, isPrefix bool) error {
67+
//Register 只要struct实现了Get(),Post(),Delete(),Put()接口就可以自动注册
68+
func Register(obj interface{}) error {
69+
return register(obj, "", false)
70+
}
71+
72+
//RegisterPrefix 注册url前缀.
73+
func RegisterPrefix(obj interface{}, path string) error {
74+
return register(obj, path, true)
75+
}
76+
77+
//RegisterPath 注册url完全匹配.
78+
func RegisterPath(obj interface{}, path string) error {
79+
return register(obj, path, true)
80+
}
81+
82+
func register(obj interface{}, path string, isPrefix bool) error {
7083
rt := reflect.TypeOf(obj)
7184
if rt.Kind() != reflect.Ptr {
7285
return fmt.Errorf("need ptr")
@@ -177,7 +190,7 @@ func (s *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
177190
return
178191
}
179192

180-
log.Debugf("%v %v %v %v", r.RemoteAddr, r.Method, r.URL, i.path)
193+
log.Debugf("%v %v %v %v", r.RemoteAddr, r.Method, r.URL, i.source)
181194

182195
callback := reflect.New(i.source).MethodByName(r.Method).Interface().(func(http.ResponseWriter, *http.Request))
183196
callback(w, nr)

main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ func (i *index) GET(w http.ResponseWriter, req *http.Request) {
2121
}
2222

2323
func testHTTPClient() {
24-
url := "http://127.0.0.1:9000/index"
24+
url := "http://127.0.0.1:9000/main/index/"
2525
buf, _, err := client.New(time.Second).Get(url, nil, nil)
2626
if err != nil {
2727
panic(err.Error())
@@ -33,7 +33,7 @@ func main() {
3333
addr := flag.String("h", ":9000", "api listen address")
3434
flag.Parse()
3535

36-
server.AddInterface(&index{}, "/index", false)
36+
server.Register(&index{})
3737

3838
go func() {
3939
for i := 0; i < 5; i++ {

server/init.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ import (
55
)
66

77
func init() {
8-
server.AddInterface(&staticServer{}, "/", true)
9-
server.AddInterface(&debugServer{}, "/debug/", true)
8+
server.RegisterPrefix(&staticServer{}, "/")
9+
server.RegisterPrefix(&debugServer{}, "/debug/")
1010

11-
server.AddInterface(&testServer{}, "/test/", false)
11+
server.RegisterPath(&testServer{}, "/test/")
1212

13-
server.AddInterface(&user{}, "", false)
13+
server.Register(&user{})
1414
}

0 commit comments

Comments
 (0)