Open geektutu opened 5 years ago
@SharkLJ 请问为什么构造POST方法就会返回404呢,用GET是正常的。下面的
r.GET
换成r.POST
就返回404func main() { r := gee.New() r.GET("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "URL.Path = %q\n", req.URL.Path) }) r.GET("/hello", func(w http.ResponseWriter, req *http.Request) { for k, v := range req.Header { fmt.Fprintf(w, "Header[%q] = %q\n", k, v) } }) r.Run(":9999") } 不是使用了,请求方法+路径拼接吗?
@ccmzd 谢谢站主提供的项目经验,我有个问题不是很懂,网上查了资料也没有找到,http.ListenAndServe(":9999", engine)第二个参数是一个interface类型,里面有有一个ServeHTTP()方法,您代码中传入了一个结构体里面有一个ServeHTTP()方法,但是并没有调用啊,怎么就执行了。结构体不是应该先赋值给接口,接口才能够调用结构体中的方法吗。在下才疏学浅,想了2天,查了百度,还是觉得迷迷糊糊的,希望大神能够赐教,感激不尽
源码中 Handler 是一个接口类型
type Handler interface { ServeHTTP(ResponseWriter, *Request) }
而我们gee
的engine
结构体实现了Handler
里面的全部方法,因此说engine
实现了接口Handler
, 所以http.ListenAndServe(addr, engine)
的engine
就是一个接口实例啦,因此允许被传递。
关于http.Handle/HndlerFunc/Handler/ServeMux等内容可以看这篇博客:https://www.alexedwards.net/blog/an-introduction-to-handlers-and-servemuxes-in-go
原来这么早就有这么好的教程了
第一步打卡
https://geektutu.com/post/gee-day1.html
7天用 Go语言 从零实现Web框架教程(7 days implement golang web framework from scratch tutorial),用 Go语言/golang 动手写Web框架,从零实现一个Web框架,从零设计一个Web框架。本文介绍了Go标准库 net/http 和 http.Handler 接口的使用,拦截所有的 HTTP 请求,交给Gee框架处理。