一、golang 路由實現的簡單思路
1、http啟動后,請求路徑時走統一的入口函數
1、通過統一函數入口,獲取request 的url路徑
2、通過對url的路徑分析,確定具體執行什么函數
二、統一入口函數
package main
import (
"io"
"net/http"
)
// 統一請求入口函數
func index(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"hello")
}
func main(){
// 啟動8083 端口
http.ListenAndServe(":8083",http.HandlerFunc(index)) // 無論路由如何去寫,都會進入到 index 函數中
}
三、解析 url 調用不同的函數
package main
import (
"io"
"net/http"
)
func index(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"index")
}
func list(w http.ResponseWriter,r *http.Request){
io.WriteString(w,"index")
}
// 解析url 函數
func router(w http.ResponseWriter,r *http.Request){
if r.RequestURI == "/"{
index(w,r)
} else if r.RequestURI == "/list" {
list(w,r)
}
}
func main(){
http.ListenAndServe(":8083",http.HandlerFunc(router))
}
四、稍微高大上一點的router 實現
package main
import (
"net/http"
)
var m *router
func init() {
m = &router{}
m.r = make(map[string]func(http.ResponseWriter, *http.Request))
}
type router struct {
r map[string]func(http.ResponseWriter, *http.Request)
}
func (this *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for k, fun := range this.r {
if k == r.RequestURI {
fun(w, r)
return
}
}
w.Write([]byte("404"))
}
func (this *router) AddRouter(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
this.r[pattern] = handlerFunc
}
func updateOne(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}
func update(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello2"))
}
func main() {
m.AddRouter("/update_one", updateOne)
m.AddRouter("/update", update)
http.ListenAndServe(":8888", m) // 一單訪問了域名便會 訪問 m 的 ServeHTTP 方法
}
如果喜歡看小說,請到183小說網
