go 簡單路由實現


一、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小說網


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM