对应视频:https://www.bilibili.com/video/BV1Xv411k7Xn
P1课程准备和一个demo
1、安装go和IDE
下载工具
2、新建一个web-tutorial文件夹
3、创建main.go
4、运行
p2:handler请求
1、处理请求:
(1)创建web server
http.ListenAndServer()
第一个参数是网络地址:如果为“”,那么就是所有网络接口的80端口。
第二个参数是handler“如果为nil,那么就是defaultServerMux
- DefaultServeMux
是一个multiplexer(可以看作是路由器) - http.Server这是一个struct
Addr字段表示网络地址:如果为”“,表示所有网络接口的80端口
handler字段:如果为nil,那就是defultServeMux
handler是一个接口
handler定义了一个方法ServeHTTP():HTTP Response Writer,指向Request这个struct的指针。
defultServeMux
是一个Multiplexer(多路复用),特也是一个handler
defultServeMux
ListenAndServe()函数
总结:两个方式创建web server
方法1 | 方法2 |
---|---|
http.Server可配置,后调用server.ListenAndaServe() | http.ListenAndServe(“localhost:8080”,nil) |
package main
import "net/http"
type myHandler struct{
}
func (m *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello SLZ"))
}
func main() {
mh := myHandler{
}
server := http.Server{
Addr: "localhost:8080",
Handler: &mh,
}
server.ListenAndServe()
//等价于:http.ListenAndServe("localhost:8080",nil)
}
(2)但是,上述方法在任何8080端口都输出同一个内容
仅http://localhost:8082/hello下展示