github地址:

https://github.com/MwlLj/go-httpserver <https://github.com/MwlLj/go-httpserver>

 

对 golang 原生的 http server 的路由功能进行增强

之前一直使用的 github.com/julienschmidt/httprouter http路由 但是对于这个路由器的一点非常不喜欢, 就是不能在
handler 函数中使用创建 handler 的类本身

所以自己重新写了一个, 可以在 handler 中获取 server 指针, 并且可以设置用户额外的参数:

type HandleFunc func(w http.ResponseWriter, r *http.Request, param CUrlParam,
server CHttpServer, userdata interface{}) bool

用户参数可以在 NewRouterHandler(userdata interface{}, handle HandleFunc) 中指定
(userdata 参数)

另外这里存在一个返回值, 如果用户返回 nil, 内部将 io.WriteString(w, "interior error")

 

example:
package main import ( "fmt" "github.com/MwlLj/go-httpserver" "io" "net/http"
"strings" ) func HandleIndex(w http.ResponseWriter, r *http.Request, param
httpserver.CUrlParam, server httpserver.CHttpServer, userdata interface{}) bool
{ s := userdata.(*CServer) s.CommonLogic() io.WriteString(w, "index") return
true } func HandleHello(w http.ResponseWriter, r *http.Request, param
httpserver.CUrlParam, server httpserver.CHttpServer, userdata interface{}) bool
{ io.WriteString(w, strings.Join([]string{"hello", *param.ByName("name")},
":")) return true } func HandleHello2(w http.ResponseWriter, r *http.Request,
param httpserver.CUrlParam, server httpserver.CHttpServer, userdata
interface{}) bool { io.WriteString(w, strings.Join([]string{"hello",
*param.ByName("name"), "age", *param.ByName("age")}, ":")) return true } func
HandleError(w http.ResponseWriter, r *http.Request, param httpserver.CUrlParam,
server httpserver.CHttpServer, userdata interface{}) bool { return false } type
CServer struct { m_http httpserver.CHttpServer } func (this *CServer)
CommonLogic() { fmt.Println("common logic") } func (this *CServer) Start() { //
new this.m_http = httpserver.NewHttpServer() // resubscribe
this.m_http.Subscribe("/", httpserver.GET, httpserver.NewRouterHandler(this,
HandleIndex)) this.m_http.Subscribe("/error", httpserver.GET,
httpserver.NewRouterHandler(this, HandleError))
this.m_http.Subscribe("/hello/:name", httpserver.GET,
httpserver.NewRouterHandler(this, HandleHello))
this.m_http.Subscribe("/hello/name/:name/age/:age", httpserver.GET,
httpserver.NewRouterHandler(this, HandleHello2)) http.ListenAndServe(":59000",
this.m_http) } func main() { server := CServer{} server.Start() }