前言
最近在学go,某天意外的看到了极客兔兔的七天用Go从零实现系列,给自己定个小目标。坚持跟极客兔兔学习go,并做个记录。
http.HandleFunc
内置的net/http包提供了http.HandleFunc方法,可以根据不同的访问路径,执行不同的代码片段
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
w.WriteHeader(200)
w.Write([]byte("index"))
})
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request){ //只要请求path等于/test,都会走这个。无关请求方式是POST、GET等
w.WriteHeader(200) //设置响应头为200
w.Write([]byte("test")) //设置响应体
})
http.ListenAndServe(":9999", nil)
}
http.ListenAndServe
http.ListenAndServe(":9999", nil),是用来启动一个web服务,其中":9999",是指监听9999端口。第二个参数,需要传入一个实现了Handler接口的实例,即实现ServeHTTP(ResponseWriter, *Request)这个方法。传nil就会走默认的实例处理(顺带说一句go里的接口实现跟ts里的差不多,更类似于一种约定,并不需要像其他面向对象语言一样使用implements关键字来实现)net/http包底层会调用这个ServeHTTP方法,所以ServeHTTP差不多是我们处理http请求的入口和关键
type engine struct {
}
func (t *engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/test" :
w.WriteHeader(201)
w.Write([]byte("test1"))
case "/" :
w.WriteHeader(201)
w.Write([]byte("index1"))
default:
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 not found"))
}
}
func main() {
http.ListenAndServe(":9999", new(engine))
}
简单静态路由
利用map将访问路径和处理handle的对应关系缓存起来实现一个简单的路由表
type HandlerFunc func( http.ResponseWriter, *http.Request)
type engine struct {
router map[string]HandlerFunc
}
func (t *engine) addRoute(method string, pattern string, handler HandlerFunc) {
key := method + "-" + pattern
t.router[key] = handler
}
func (t *engine) GET(pattern string, handler HandlerFunc) {
t.addRoute("GET", pattern, handler)
}
func (t *engine) POST(pattern string, handler HandlerFunc) {
t.addRoute("POST", pattern, handler)
}
func (t *engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
key := r.Method + "-" + r.URL.Path
if handle, ok := t.router[key]; ok {
handle(w, r)
} else {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("not found"))
}
}
func main() {
engine := new(engine)
engine.router = make(map[string]HandlerFunc)
engine.GET("/test", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("test"))
})
engine.POST("/test", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
log.Println(r.Header)
s,_ := ioutil.ReadAll(r.Body)
w.Write(s)
})
http.ListenAndServe(":9999", engine)
}
网友评论