go 简单路由实现

摘要:
r*http.Request){ifr.RequestURI==“/”{index(w,router{}m.r=make(map[string]func(http.ResponseWriter,

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

免责声明:文章转载自《go 简单路由实现》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇甘特图收集GoldenDict(for Linux)配置无道词典下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

LUA 利用#遍历表的问题

1 tb ={ '0','1',2} 2 t = { 3 "hello", 4 1, 5 2, 6 'w', 7 4, 8 tb 9 } 10 11 --~ 1 hello 12 --~ 2 1 13 --~ 3 2 14 --~ 4 w 15 --~ 5 4...

C# 如何获取Url的host以及是否是http

参考资料:https://sites.google.com/site/netcorenote/asp-net-core/get-scheme-url-host Example there's an given url: http://localhost:4800/account/login 获取整个url地址: 在页面(cstml)中  Microsoft...

投影变换 到 uv坐标 xy/w 齐次坐标

float3 vScreenPos = In.ClipPos.xyz; vScreenPos /= In.ClipPos.w; vScreenPos.xy += 1.f; vScreenPos.xy *= 0.5f; vScreenPos.y = 1.f - vScreenPos.y; 这个是shader里从vertex最后那个pos 里取 uv的算法 p...

tf.GradientTape() 使用

import tensorflow as tfw = tf.constant(1.)x = tf.constant(2.)y = x*wwith tf.GradientTape() as tape: tape.watch([w]) y2 = x*wgrad1 = tape.gradient(y,[w])print(grad1)结果为[None...