From 8bc0fd463d4e2a1ed7f5009cf254c96022b5904a Mon Sep 17 00:00:00 2001 From: Millyn Date: Sat, 31 Jul 2021 15:13:08 +0800 Subject: [PATCH 01/10] learn http server --- console.go | 11 +++++++++++ context.go | 1 + router.go | 11 +++++++++++ wkws.go | 27 ++++++++++++++++++++++++--- wkws_test.go | 31 +++++++++++++++++++++++++++++++ 5 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 console.go create mode 100644 context.go create mode 100644 router.go create mode 100644 wkws_test.go diff --git a/console.go b/console.go new file mode 100644 index 0000000..7226878 --- /dev/null +++ b/console.go @@ -0,0 +1,11 @@ +package wkwsweb + +import "fmt" + +const ( + PREFIX = "[WKWS]" +) + +func CLogger(s string, v ...interface{}) { + fmt.Printf(PREFIX+s+"\n", v...) +} diff --git a/context.go b/context.go new file mode 100644 index 0000000..7d8e731 --- /dev/null +++ b/context.go @@ -0,0 +1 @@ +package wkwsweb diff --git a/router.go b/router.go new file mode 100644 index 0000000..ba5f986 --- /dev/null +++ b/router.go @@ -0,0 +1,11 @@ +package wkwsweb + +import "net/http" + +func (wkws *Wkws) POST(uri string, handler http.HandlerFunc) { + wkws.Router.HandleFunc(uri, handler) +} + +func (wkws *Wkws) GET(uri string, handler http.HandlerFunc) { + wkws.Router.HandleFunc(uri, handler) +} diff --git a/wkws.go b/wkws.go index 51e61e4..6e2750b 100644 --- a/wkws.go +++ b/wkws.go @@ -1,6 +1,27 @@ package wkwsweb -type wkws struct { - Address string - Port string +import ( + "net/http" +) + +type Wkws struct { + Address string `json:"address"` + Port string `json:"port"` + Router *http.ServeMux +} + +func Init(add string, port string) (core *Wkws) { + core = &Wkws{ + Address: add, + Port: port, + Router: http.NewServeMux(), + } + return +} + +func (wkws *Wkws) Run() (err error) { + addr := wkws.Address + ":" + wkws.Port + CLogger("HTTP listen the address , %s \n", addr) + err = http.ListenAndServe(addr, wkws.Router) + return } diff --git a/wkws_test.go b/wkws_test.go new file mode 100644 index 0000000..52d8545 --- /dev/null +++ b/wkws_test.go @@ -0,0 +1,31 @@ +package wkwsweb + +import ( + "log" + "net/http" + "testing" +) + +func PostController(rsp http.ResponseWriter, req *http.Request) { + _, err := rsp.Write([]byte("The is POST method")) + if err != nil { + return + } +} + +func GetController(rsp http.ResponseWriter, req *http.Request) { + _, err := rsp.Write([]byte("The is GET method")) + if err != nil { + return + } +} + +func TestWkws_Run(t *testing.T) { + core := Init("0.0.0.0", "8081") + core.POST("/post", PostController) + core.GET("/get", GetController) + err := core.Run() + if err != nil { + log.Println(err) + } +} From 7df10191fa601fbbb76d3002f9aa547465d9b55e Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 2 Aug 2021 13:31:33 +0800 Subject: [PATCH 02/10] add Router method verify and routergroup --- context.go | 11 +++++++++++ router.go | 20 ++++++++++++++++++-- router_test.go | 12 ++++++++++++ utils.go | 10 ++++++++++ wkws.go | 45 ++++++++++++++++++++++++++++++++++++++------- 5 files changed, 89 insertions(+), 9 deletions(-) create mode 100644 router_test.go create mode 100644 utils.go diff --git a/context.go b/context.go index 7d8e731..8d7fa4d 100644 --- a/context.go +++ b/context.go @@ -1 +1,12 @@ package wkwsweb + +import "net/http" + +type Context struct { + Request *http.Request + http.ResponseWriter + size int + status int + index int8 + fullPath string +} diff --git a/router.go b/router.go index ba5f986..635560c 100644 --- a/router.go +++ b/router.go @@ -2,10 +2,26 @@ package wkwsweb import "net/http" +type Routers []Router + +type Router struct { + Handler http.HandlerFunc + Path string + Method string +} + func (wkws *Wkws) POST(uri string, handler http.HandlerFunc) { - wkws.Router.HandleFunc(uri, handler) + AddRouter(http.MethodPost, uri, handler, wkws) } func (wkws *Wkws) GET(uri string, handler http.HandlerFunc) { - wkws.Router.HandleFunc(uri, handler) + AddRouter(http.MethodGet, uri, handler, wkws) +} + +func AddRouter(method string, path string, handler http.HandlerFunc, core *Wkws) { + core.RouterGroup = append(core.RouterGroup, Router{ + Handler: handler, + Path: path, + Method: method, + }) } diff --git a/router_test.go b/router_test.go new file mode 100644 index 0000000..5ce9bd1 --- /dev/null +++ b/router_test.go @@ -0,0 +1,12 @@ +package wkwsweb + +import "testing" + +func TestRouters(t *testing.T) { + wkws := Init("0.0.0.0", "8081") + wkws.POST("/hello", wkws.ServeHTTP) + err := wkws.Run() + if err != nil { + return + } +} diff --git a/utils.go b/utils.go new file mode 100644 index 0000000..036ae01 --- /dev/null +++ b/utils.go @@ -0,0 +1,10 @@ +package wkwsweb + +func ServerFailed(c *Context) { + c.ResponseWriter.WriteHeader(405) + _, err := c.ResponseWriter.Write([]byte("405 method not allowed")) + if err != nil { + CLogger("cannot write message %v", err) + } + return +} diff --git a/wkws.go b/wkws.go index 6e2750b..1f68cf0 100644 --- a/wkws.go +++ b/wkws.go @@ -5,16 +5,16 @@ import ( ) type Wkws struct { - Address string `json:"address"` - Port string `json:"port"` - Router *http.ServeMux + Address string `json:"address"` + Port string `json:"port"` + RouterGroup Routers } func Init(add string, port string) (core *Wkws) { core = &Wkws{ - Address: add, - Port: port, - Router: http.NewServeMux(), + Address: add, + Port: port, + RouterGroup: nil, } return } @@ -22,6 +22,37 @@ func Init(add string, port string) (core *Wkws) { func (wkws *Wkws) Run() (err error) { addr := wkws.Address + ":" + wkws.Port CLogger("HTTP listen the address , %s \n", addr) - err = http.ListenAndServe(addr, wkws.Router) + r := http.NewServeMux() + CLogger("Router map:") + for _, router := range wkws.RouterGroup { + r.HandleFunc(router.Path, router.Handler) + CLogger(router.Method + " " + router.Path) + } + err = http.ListenAndServe(addr, r) return } + +func (wkws *Wkws) ServeHTTP(rsp http.ResponseWriter, req *http.Request) { + c := Context{} + c.Request = req + c.ResponseWriter = rsp + wkws.CheckMethod(&c) +} + +func (wkws *Wkws) CheckMethod(c *Context) { + verify := wkws.VerifyMethod(c.Request.RequestURI, c.Request.Method) + if !verify { + ServerFailed(c) + return + } + c.ResponseWriter.Write([]byte("Hello World")) +} + +func (wkws *Wkws) VerifyMethod(path string, method string) bool { + for _, r := range wkws.RouterGroup { + if r.Path == path && r.Method == method { + return true + } + } + return false +} From 9657bbf8a850d95203a5e4fb689907444d9ca586 Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 2 Aug 2021 14:00:12 +0800 Subject: [PATCH 03/10] Register Controller to router group and callback controller --- context.go | 6 ++---- router.go | 8 ++++---- router_test.go | 11 ----------- utils.go | 8 ++++++++ wkws.go | 26 +++++++++++++++++--------- wkws_test.go | 15 ++++----------- 6 files changed, 35 insertions(+), 39 deletions(-) diff --git a/context.go b/context.go index 8d7fa4d..3a44fbf 100644 --- a/context.go +++ b/context.go @@ -5,8 +5,6 @@ import "net/http" type Context struct { Request *http.Request http.ResponseWriter - size int - status int - index int8 - fullPath string } + +type Controller func(ctx *Context) diff --git a/router.go b/router.go index 635560c..ec63c6b 100644 --- a/router.go +++ b/router.go @@ -5,20 +5,20 @@ import "net/http" type Routers []Router type Router struct { - Handler http.HandlerFunc + Handler Controller Path string Method string } -func (wkws *Wkws) POST(uri string, handler http.HandlerFunc) { +func (wkws *Wkws) POST(uri string, handler Controller) { AddRouter(http.MethodPost, uri, handler, wkws) } -func (wkws *Wkws) GET(uri string, handler http.HandlerFunc) { +func (wkws *Wkws) GET(uri string, handler Controller) { AddRouter(http.MethodGet, uri, handler, wkws) } -func AddRouter(method string, path string, handler http.HandlerFunc, core *Wkws) { +func AddRouter(method string, path string, handler Controller, core *Wkws) { core.RouterGroup = append(core.RouterGroup, Router{ Handler: handler, Path: path, diff --git a/router_test.go b/router_test.go index 5ce9bd1..7d8e731 100644 --- a/router_test.go +++ b/router_test.go @@ -1,12 +1 @@ package wkwsweb - -import "testing" - -func TestRouters(t *testing.T) { - wkws := Init("0.0.0.0", "8081") - wkws.POST("/hello", wkws.ServeHTTP) - err := wkws.Run() - if err != nil { - return - } -} diff --git a/utils.go b/utils.go index 036ae01..2d2cbac 100644 --- a/utils.go +++ b/utils.go @@ -8,3 +8,11 @@ func ServerFailed(c *Context) { } return } + +type WkwsError struct { + Msg string +} + +func (e *WkwsError) Error() string { + return e.Msg +} diff --git a/wkws.go b/wkws.go index 1f68cf0..c013122 100644 --- a/wkws.go +++ b/wkws.go @@ -4,6 +4,10 @@ import ( "net/http" ) +type Error struct { + Err error +} + type Wkws struct { Address string `json:"address"` Port string `json:"port"` @@ -25,7 +29,7 @@ func (wkws *Wkws) Run() (err error) { r := http.NewServeMux() CLogger("Router map:") for _, router := range wkws.RouterGroup { - r.HandleFunc(router.Path, router.Handler) + r.HandleFunc(router.Path, wkws.ServeHTTP) CLogger(router.Method + " " + router.Path) } err = http.ListenAndServe(addr, r) @@ -36,23 +40,27 @@ func (wkws *Wkws) ServeHTTP(rsp http.ResponseWriter, req *http.Request) { c := Context{} c.Request = req c.ResponseWriter = rsp - wkws.CheckMethod(&c) + controller, err := wkws.CheckMethod(&c) + if err != nil { + return + } + controller(&c) } -func (wkws *Wkws) CheckMethod(c *Context) { - verify := wkws.VerifyMethod(c.Request.RequestURI, c.Request.Method) +func (wkws *Wkws) CheckMethod(c *Context) (Controller, error) { + handler, verify := wkws.VerifyMethod(c.Request.RequestURI, c.Request.Method) if !verify { ServerFailed(c) - return + return nil, &WkwsError{Msg: "error"} } - c.ResponseWriter.Write([]byte("Hello World")) + return handler, nil } -func (wkws *Wkws) VerifyMethod(path string, method string) bool { +func (wkws *Wkws) VerifyMethod(path string, method string) (Controller, bool) { for _, r := range wkws.RouterGroup { if r.Path == path && r.Method == method { - return true + return r.Handler, true } } - return false + return nil, false } diff --git a/wkws_test.go b/wkws_test.go index 52d8545..e74727f 100644 --- a/wkws_test.go +++ b/wkws_test.go @@ -2,22 +2,15 @@ package wkwsweb import ( "log" - "net/http" "testing" ) -func PostController(rsp http.ResponseWriter, req *http.Request) { - _, err := rsp.Write([]byte("The is POST method")) - if err != nil { - return - } +func PostController(ctx *Context) { + ctx.ResponseWriter.Write([]byte("This is Post Controller")) } -func GetController(rsp http.ResponseWriter, req *http.Request) { - _, err := rsp.Write([]byte("The is GET method")) - if err != nil { - return - } +func GetController(ctx *Context) { + ctx.ResponseWriter.Write([]byte("This is Get Controller")) } func TestWkws_Run(t *testing.T) { From aa6bbcb1d712fb81bed8161287a7dea08f13724f Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 2 Aug 2021 15:05:46 +0800 Subject: [PATCH 04/10] fix uri && add Params struct --- context.go | 36 ++++++++++++++++++++++++++++++++++++ utils.go | 9 --------- wkws.go | 30 ++++++++++++++++++------------ wkws_test.go | 19 +++++++++++++++++-- 4 files changed, 71 insertions(+), 23 deletions(-) diff --git a/context.go b/context.go index 3a44fbf..52c145e 100644 --- a/context.go +++ b/context.go @@ -2,9 +2,45 @@ package wkwsweb import "net/http" +type Param struct { + Key string + Value string +} + +type Params []Param + type Context struct { Request *http.Request http.ResponseWriter + Cache map[string]interface{} + Params Params } type Controller func(ctx *Context) + +func NewCtx() *Context { + return &Context{ + nil, + nil, + map[string]interface{}{}, + make(Params, 0, 100), + } +} + +func (ps Params) Get(name string) (string, bool) { + for _, entry := range ps { + if entry.Key == name { + return entry.Value, true + } + } + return "", false +} + +func (ctx *Context) Set(key string, value interface{}) { + ctx.Cache[key] = value +} + +func (ctx *Context) Get(key string) interface{} { + value := ctx.Cache[key] + return value +} diff --git a/utils.go b/utils.go index 2d2cbac..b03ca51 100644 --- a/utils.go +++ b/utils.go @@ -1,14 +1,5 @@ package wkwsweb -func ServerFailed(c *Context) { - c.ResponseWriter.WriteHeader(405) - _, err := c.ResponseWriter.Write([]byte("405 method not allowed")) - if err != nil { - CLogger("cannot write message %v", err) - } - return -} - type WkwsError struct { Msg string } diff --git a/wkws.go b/wkws.go index c013122..49d584e 100644 --- a/wkws.go +++ b/wkws.go @@ -9,22 +9,18 @@ type Error struct { } type Wkws struct { - Address string `json:"address"` - Port string `json:"port"` RouterGroup Routers } -func Init(add string, port string) (core *Wkws) { +func Init() (core *Wkws) { core = &Wkws{ - Address: add, - Port: port, RouterGroup: nil, } return } -func (wkws *Wkws) Run() (err error) { - addr := wkws.Address + ":" + wkws.Port +func (wkws *Wkws) Run(add string, port string) (err error) { + addr := add + ":" + port CLogger("HTTP listen the address , %s \n", addr) r := http.NewServeMux() CLogger("Router map:") @@ -37,22 +33,23 @@ func (wkws *Wkws) Run() (err error) { } func (wkws *Wkws) ServeHTTP(rsp http.ResponseWriter, req *http.Request) { - c := Context{} + c := NewCtx() c.Request = req c.ResponseWriter = rsp - controller, err := wkws.CheckMethod(&c) + controller, err := wkws.HandlerHttpRequest(c) if err != nil { return } - controller(&c) + controller(c) } -func (wkws *Wkws) CheckMethod(c *Context) (Controller, error) { - handler, verify := wkws.VerifyMethod(c.Request.RequestURI, c.Request.Method) +func (wkws *Wkws) HandlerHttpRequest(c *Context) (Controller, error) { + handler, verify := wkws.VerifyMethod(c.Request.URL.Path, c.Request.Method) if !verify { ServerFailed(c) return nil, &WkwsError{Msg: "error"} } + // TODO Handler Request Params return handler, nil } @@ -64,3 +61,12 @@ func (wkws *Wkws) VerifyMethod(path string, method string) (Controller, bool) { } return nil, false } + +func ServerFailed(c *Context) { + c.ResponseWriter.WriteHeader(405) + _, err := c.ResponseWriter.Write([]byte("405 method not allowed")) + if err != nil { + CLogger("cannot write message %v", err) + } + return +} diff --git a/wkws_test.go b/wkws_test.go index e74727f..0177dde 100644 --- a/wkws_test.go +++ b/wkws_test.go @@ -13,11 +13,26 @@ func GetController(ctx *Context) { ctx.ResponseWriter.Write([]byte("This is Get Controller")) } +func CacheController(ctx *Context) { + ctx.Set("Hello", "World") + bytes := []byte("Cache : " + ctx.Get("Hello").(string)) + ctx.ResponseWriter.Write(bytes) +} + func TestWkws_Run(t *testing.T) { - core := Init("0.0.0.0", "8081") + core := Init() core.POST("/post", PostController) core.GET("/get", GetController) - err := core.Run() + err := core.Run("0.0.0.0", "8081") + if err != nil { + log.Println(err) + } +} + +func TestWkws_ContextCache(t *testing.T) { + core := Init() + core.GET("/cache", CacheController) + err := core.Run("0.0.0.0", "8081") if err != nil { log.Println(err) } From b26ba176df33c4c61f9d5165e01490a48d96013a Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 2 Aug 2021 15:52:07 +0800 Subject: [PATCH 05/10] add response JSON --- context.go | 18 +++++++++++++++++- utils.go | 3 +++ wkws_test.go | 7 +++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 52c145e..6a91fe2 100644 --- a/context.go +++ b/context.go @@ -1,6 +1,9 @@ package wkwsweb -import "net/http" +import ( + "encoding/json" + "net/http" +) type Param struct { Key string @@ -44,3 +47,16 @@ func (ctx *Context) Get(key string) interface{} { value := ctx.Cache[key] return value } + +func (ctx *Context) ResponseJSON(data interface{}) { + ctx.ResponseWriter.Header().Add("Content-type", "application/json") + marshal, err := json.Marshal(data) + if err != nil { + return + } + _, err = ctx.ResponseWriter.Write(marshal) + if err != nil { + CLogger("Cannot write response json %v", err) + return + } +} diff --git a/utils.go b/utils.go index b03ca51..c145771 100644 --- a/utils.go +++ b/utils.go @@ -1,5 +1,8 @@ package wkwsweb +// H is a shortcut for map[string]interface{} +type H map[string]interface{} + type WkwsError struct { Msg string } diff --git a/wkws_test.go b/wkws_test.go index 0177dde..72a191c 100644 --- a/wkws_test.go +++ b/wkws_test.go @@ -19,6 +19,12 @@ func CacheController(ctx *Context) { ctx.ResponseWriter.Write(bytes) } +func ResponseController(ctx *Context) { + ctx.ResponseJSON(H{ + "HelloWorld": "Millyn", + }) +} + func TestWkws_Run(t *testing.T) { core := Init() core.POST("/post", PostController) @@ -32,6 +38,7 @@ func TestWkws_Run(t *testing.T) { func TestWkws_ContextCache(t *testing.T) { core := Init() core.GET("/cache", CacheController) + core.GET("/response", ResponseController) err := core.Run("0.0.0.0", "8081") if err != nil { log.Println(err) From d188e77821f846e021a2673c754053323a8c2039 Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 2 Aug 2021 16:10:05 +0800 Subject: [PATCH 06/10] Rename function --- wkws.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wkws.go b/wkws.go index 49d584e..9cc5f30 100644 --- a/wkws.go +++ b/wkws.go @@ -46,7 +46,7 @@ func (wkws *Wkws) ServeHTTP(rsp http.ResponseWriter, req *http.Request) { func (wkws *Wkws) HandlerHttpRequest(c *Context) (Controller, error) { handler, verify := wkws.VerifyMethod(c.Request.URL.Path, c.Request.Method) if !verify { - ServerFailed(c) + ServerMethodsNotAllowed(c) return nil, &WkwsError{Msg: "error"} } // TODO Handler Request Params @@ -62,7 +62,7 @@ func (wkws *Wkws) VerifyMethod(path string, method string) (Controller, bool) { return nil, false } -func ServerFailed(c *Context) { +func ServerMethodsNotAllowed(c *Context) { c.ResponseWriter.WriteHeader(405) _, err := c.ResponseWriter.Write([]byte("405 method not allowed")) if err != nil { From 617bc241b0b34cdabe9219ff2cf8e8623f2e08c2 Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 2 Aug 2021 17:09:53 +0800 Subject: [PATCH 07/10] reanme funciton and add todo --- wkws.go | 10 ++++++---- wkws_test.go | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/wkws.go b/wkws.go index 9cc5f30..4d08aaa 100644 --- a/wkws.go +++ b/wkws.go @@ -24,6 +24,7 @@ func (wkws *Wkws) Run(add string, port string) (err error) { CLogger("HTTP listen the address , %s \n", addr) r := http.NewServeMux() CLogger("Router map:") + // TODO handler same path diff method for _, router := range wkws.RouterGroup { r.HandleFunc(router.Path, wkws.ServeHTTP) CLogger(router.Method + " " + router.Path) @@ -36,24 +37,25 @@ func (wkws *Wkws) ServeHTTP(rsp http.ResponseWriter, req *http.Request) { c := NewCtx() c.Request = req c.ResponseWriter = rsp - controller, err := wkws.HandlerHttpRequest(c) + controller, err := wkws.handlerHttpRequest(c) if err != nil { return } controller(c) } -func (wkws *Wkws) HandlerHttpRequest(c *Context) (Controller, error) { - handler, verify := wkws.VerifyMethod(c.Request.URL.Path, c.Request.Method) +func (wkws *Wkws) handlerHttpRequest(c *Context) (Controller, error) { + handler, verify := wkws.handlerVerifyRouter(c.Request.URL.Path, c.Request.Method) if !verify { ServerMethodsNotAllowed(c) return nil, &WkwsError{Msg: "error"} } // TODO Handler Request Params + // for that c.Request.URL.Query() , key is value value is key. return handler, nil } -func (wkws *Wkws) VerifyMethod(path string, method string) (Controller, bool) { +func (wkws *Wkws) handlerVerifyRouter(path string, method string) (Controller, bool) { for _, r := range wkws.RouterGroup { if r.Path == path && r.Method == method { return r.Handler, true diff --git a/wkws_test.go b/wkws_test.go index 72a191c..43fbb71 100644 --- a/wkws_test.go +++ b/wkws_test.go @@ -39,6 +39,7 @@ func TestWkws_ContextCache(t *testing.T) { core := Init() core.GET("/cache", CacheController) core.GET("/response", ResponseController) + core.POST("/response", ResponseController) err := core.Run("0.0.0.0", "8081") if err != nil { log.Println(err) From f584793cc662de9470130a4dd00112ceafe62db4 Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 23 Aug 2021 15:54:18 +0800 Subject: [PATCH 08/10] fix repeat router register bug --- binding.go | 16 ++++++++++++++++ context.go | 8 ++++++++ router.go | 14 ++++++++------ wkws.go | 23 ++++++++++++++++------- wkws_test.go | 27 ++++++++++++--------------- 5 files changed, 60 insertions(+), 28 deletions(-) create mode 100644 binding.go diff --git a/binding.go b/binding.go new file mode 100644 index 0000000..a8cb1f8 --- /dev/null +++ b/binding.go @@ -0,0 +1,16 @@ +package wkwsweb + +// Content-Type MINE of the most common data formats. by Gin +const ( + MIMEJSON = "application/json" + MIMEHTML = "text/html" + MIMEXML = "application/xml" + MIMEXML2 = "text/xml" + MIMEPlain = "text/plain" + MIMEPOSTForm = "application/x-www-form-urlencoded" + MIMEMultipartPOSTForm = "multipart/form-data" + MIMEPROTOBUF = "application/x-protobuf" + MIMEMSGPACK = "application/x-msgpack" + MIMEMSGPACK2 = "application/msgpack" + MIMEYAML = "application/x-yaml" +) diff --git a/context.go b/context.go index 6a91fe2..b444ae3 100644 --- a/context.go +++ b/context.go @@ -48,6 +48,14 @@ func (ctx *Context) Get(key string) interface{} { return value } +func (ctx *Context) GetMap() map[string][]string { + return ctx.Request.PostForm +} + +func (ctx *Context) GetRequestContext() string { + return ctx.Request.Header["Content-Type"][0] +} + func (ctx *Context) ResponseJSON(data interface{}) { ctx.ResponseWriter.Header().Add("Content-type", "application/json") marshal, err := json.Marshal(data) diff --git a/router.go b/router.go index ec63c6b..a8a4573 100644 --- a/router.go +++ b/router.go @@ -1,13 +1,15 @@ package wkwsweb -import "net/http" +import ( + "net/http" +) -type Routers []Router +type RouterHandlers []RouterHandler -type Router struct { - Handler Controller +type RouterHandler struct { Path string Method string + Handler Controller } func (wkws *Wkws) POST(uri string, handler Controller) { @@ -19,9 +21,9 @@ func (wkws *Wkws) GET(uri string, handler Controller) { } func AddRouter(method string, path string, handler Controller, core *Wkws) { - core.RouterGroup = append(core.RouterGroup, Router{ - Handler: handler, + core.RouterHandlers = append(core.RouterHandlers, RouterHandler{ Path: path, Method: method, + Handler: handler, }) } diff --git a/wkws.go b/wkws.go index 4d08aaa..9d96b84 100644 --- a/wkws.go +++ b/wkws.go @@ -9,12 +9,13 @@ type Error struct { } type Wkws struct { - RouterGroup Routers + RouterHandlers RouterHandlers + HttpServer *http.Server } func Init() (core *Wkws) { core = &Wkws{ - RouterGroup: nil, + RouterHandlers: nil, } return } @@ -25,11 +26,19 @@ func (wkws *Wkws) Run(add string, port string) (err error) { r := http.NewServeMux() CLogger("Router map:") // TODO handler same path diff method - for _, router := range wkws.RouterGroup { - r.HandleFunc(router.Path, wkws.ServeHTTP) - CLogger(router.Method + " " + router.Path) + // Get new routers, filter router path repeat + + registeredRouter := map[string]struct{}{} + + for _, router := range wkws.RouterHandlers { + if _, exist := registeredRouter[router.Path]; !exist { + r.HandleFunc(router.Path, wkws.ServeHTTP) + registeredRouter[router.Path] = struct{}{} + } + CLogger("Router Method is %s , Path in %s , Handler is %s", router.Method, router.Path, router.Handler) } - err = http.ListenAndServe(addr, r) + wkws.HttpServer = &http.Server{Addr: addr, Handler: r} + err = wkws.HttpServer.ListenAndServe() return } @@ -56,7 +65,7 @@ func (wkws *Wkws) handlerHttpRequest(c *Context) (Controller, error) { } func (wkws *Wkws) handlerVerifyRouter(path string, method string) (Controller, bool) { - for _, r := range wkws.RouterGroup { + for _, r := range wkws.RouterHandlers { if r.Path == path && r.Method == method { return r.Handler, true } diff --git a/wkws_test.go b/wkws_test.go index 43fbb71..cd29bd1 100644 --- a/wkws_test.go +++ b/wkws_test.go @@ -2,10 +2,15 @@ package wkwsweb import ( "log" + "net/http/httptest" "testing" ) func PostController(ctx *Context) { + log.Println(ctx.GetMap()) + log.Println(ctx.Request.Method) + log.Println(ctx.Request.Header["Content-Type"]) + log.Println(ctx.GetRequestContext()) ctx.ResponseWriter.Write([]byte("This is Post Controller")) } @@ -25,23 +30,15 @@ func ResponseController(ctx *Context) { }) } -func TestWkws_Run(t *testing.T) { - core := Init() - core.POST("/post", PostController) - core.GET("/get", GetController) - err := core.Run("0.0.0.0", "8081") - if err != nil { - log.Println(err) - } -} - -func TestWkws_ContextCache(t *testing.T) { +func TestWkws_HttpRun(t *testing.T) { core := Init() core.GET("/cache", CacheController) core.GET("/response", ResponseController) core.POST("/response", ResponseController) - err := core.Run("0.0.0.0", "8081") - if err != nil { - log.Println(err) - } + + var ts *httptest.Server + + ts = httptest.NewServer(core) + + defer ts.Close() } From f68fc62177f3fd1e41db631d93f5fa961e7175d3 Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 23 Aug 2021 16:22:45 +0800 Subject: [PATCH 09/10] private addrouter function && remove TODO --- router.go | 6 +++--- wkws.go | 2 -- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/router.go b/router.go index a8a4573..844126f 100644 --- a/router.go +++ b/router.go @@ -13,14 +13,14 @@ type RouterHandler struct { } func (wkws *Wkws) POST(uri string, handler Controller) { - AddRouter(http.MethodPost, uri, handler, wkws) + addRouter(http.MethodPost, uri, handler, wkws) } func (wkws *Wkws) GET(uri string, handler Controller) { - AddRouter(http.MethodGet, uri, handler, wkws) + addRouter(http.MethodGet, uri, handler, wkws) } -func AddRouter(method string, path string, handler Controller, core *Wkws) { +func addRouter(method string, path string, handler Controller, core *Wkws) { core.RouterHandlers = append(core.RouterHandlers, RouterHandler{ Path: path, Method: method, diff --git a/wkws.go b/wkws.go index 9d96b84..3be31d3 100644 --- a/wkws.go +++ b/wkws.go @@ -25,9 +25,7 @@ func (wkws *Wkws) Run(add string, port string) (err error) { CLogger("HTTP listen the address , %s \n", addr) r := http.NewServeMux() CLogger("Router map:") - // TODO handler same path diff method // Get new routers, filter router path repeat - registeredRouter := map[string]struct{}{} for _, router := range wkws.RouterHandlers { From 9ce4e4ada2db389bcd43c8f675d9fef31613ae82 Mon Sep 17 00:00:00 2001 From: Millyn Date: Mon, 23 Aug 2021 16:24:08 +0800 Subject: [PATCH 10/10] init Httpserver is nil --- wkws.go | 1 + 1 file changed, 1 insertion(+) diff --git a/wkws.go b/wkws.go index 3be31d3..a31ed2e 100644 --- a/wkws.go +++ b/wkws.go @@ -16,6 +16,7 @@ type Wkws struct { func Init() (core *Wkws) { core = &Wkws{ RouterHandlers: nil, + HttpServer: nil, } return }