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小说网

原文地址:https://www.cnblogs.com/xiaobaiskill/p/10832066.html