geektutu / blog

极客兔兔的博客,Coding Coding 创建有趣的开源项目。
https://geektutu.com
Apache License 2.0
167 stars 21 forks source link

Go语言动手写Web框架 - Gee第一天 http.Handler | 极客兔兔 #37

Open geektutu opened 5 years ago

geektutu commented 5 years ago

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框架处理。

lzb200244 commented 1 year ago

1

@SharkLJ 请问为什么构造POST方法就会返回404呢,用GET是正常的。下面的r.GET换成r.POST就返回404


func 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")
}
不是使用了,请求方法+路径拼接吗?
lv997 commented 10 months ago

@ccmzd 谢谢站主提供的项目经验,我有个问题不是很懂,网上查了资料也没有找到,http.ListenAndServe(":9999", engine)第二个参数是一个interface类型,里面有有一个ServeHTTP()方法,您代码中传入了一个结构体里面有一个ServeHTTP()方法,但是并没有调用啊,怎么就执行了。结构体不是应该先赋值给接口,接口才能够调用结构体中的方法吗。在下才疏学浅,想了2天,查了百度,还是觉得迷迷糊糊的,希望大神能够赐教,感激不尽

源码中 Handler 是一个接口类型 type Handler interface { ServeHTTP(ResponseWriter, *Request) } 而我们geeengine结构体实现了Handler里面的全部方法,因此说engine实现了接口Handler, 所以http.ListenAndServe(addr, engine)engine就是一个接口实例啦,因此允许被传递。

coderZoe commented 3 months ago

关于http.Handle/HndlerFunc/Handler/ServeMux等内容可以看这篇博客:https://www.alexedwards.net/blog/an-introduction-to-handlers-and-servemuxes-in-go

ToTrooo commented 1 month ago

原来这么早就有这么好的教程了

lingaoliu105 commented 1 month ago

第一步打卡