Skip to content

Commit

Permalink
http模块修改完成
Browse files Browse the repository at this point in the history
  • Loading branch information
c-wind committed Sep 16, 2017
1 parent 43df0be commit 067898e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
21 changes: 17 additions & 4 deletions http/server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,22 @@ func NameToPath(name string, depth int) string {
return string(buf[index:])
}

//AddInterface 自动注册接口
//只要struct实现了Get(),Post(),Delete(),Put()接口就可以自动注册
func AddInterface(obj interface{}, path string, isPrefix bool) error {
//Register 只要struct实现了Get(),Post(),Delete(),Put()接口就可以自动注册
func Register(obj interface{}) error {
return register(obj, "", false)
}

//RegisterPrefix 注册url前缀.
func RegisterPrefix(obj interface{}, path string) error {
return register(obj, path, true)
}

//RegisterPath 注册url完全匹配.
func RegisterPath(obj interface{}, path string) error {
return register(obj, path, true)
}

func register(obj interface{}, path string, isPrefix bool) error {
rt := reflect.TypeOf(obj)
if rt.Kind() != reflect.Ptr {
return fmt.Errorf("need ptr")
Expand Down Expand Up @@ -177,7 +190,7 @@ func (s *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}

log.Debugf("%v %v %v %v", r.RemoteAddr, r.Method, r.URL, i.path)
log.Debugf("%v %v %v %v", r.RemoteAddr, r.Method, r.URL, i.source)

callback := reflect.New(i.source).MethodByName(r.Method).Interface().(func(http.ResponseWriter, *http.Request))
callback(w, nr)
Expand Down
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (i *index) GET(w http.ResponseWriter, req *http.Request) {
}

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

server.AddInterface(&index{}, "/index", false)
server.Register(&index{})

go func() {
for i := 0; i < 5; i++ {
Expand Down
8 changes: 4 additions & 4 deletions server/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
)

func init() {
server.AddInterface(&staticServer{}, "/", true)
server.AddInterface(&debugServer{}, "/debug/", true)
server.RegisterPrefix(&staticServer{}, "/")
server.RegisterPrefix(&debugServer{}, "/debug/")

server.AddInterface(&testServer{}, "/test/", false)
server.RegisterPath(&testServer{}, "/test/")

server.AddInterface(&user{}, "", false)
server.Register(&user{})
}

0 comments on commit 067898e

Please sign in to comment.