golang http 路由
github地址:https://github.com/MwlLj/go-httpserver 对 golang 原生的 http server 的路由功能进行增强之前一直使用的 github.com/julienschmidt/httprouter http路由 但是对于这个路由器的一点非常不喜欢, 就是不能在 handler 函数中使用创建 handler 的类本身所以自己...
github地址:
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()
}
「智能机器人开发者大赛」官方平台,致力于为开发者和参赛选手提供赛事技术指导、行业标准解读及团队实战案例解析;聚焦智能机器人开发全栈技术闭环,助力开发者攻克技术瓶颈,促进软硬件集成、场景应用及商业化落地的深度研讨。 加入智能机器人开发者社区iRobot Developer,与全球极客并肩突破技术边界,定义机器人开发的未来范式!
更多推荐
所有评论(0)