Web 应用
Web 应用
package main
import (
"fmt"
"log"
"net/http"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println("path:", r.URL.Path)
fmt.Fprintf(w, "hello go")
}
func main() {
http.HandleFunc("/", sayHelloName)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServer: ", err)
}
}
HTTP 包运行机制
-
创建
Listen Socket
, 监听指定的端口, 等待客户端请求到来。 -
Listen Socket
接受客户端的请求, 得到Client Socket
, 接下来通过Client Socket
与客户端通信。 -
处理客户端的请求
, 首先从Client Socket
读取HTTP 请求, 然后交给相应的handler
处理请求, 最后将handler
处理完毕的数据, 通过Client Socket
写给客户端。
其中涉及服务器端的概念
- Request:用户请求的信息,用来解析用户的请求信息,包括
post 、get、cookie、url 等信息 - Conn:用户的每次请求链接
- Handler:处理请求和生成返回信息的处理逻辑
- Response:服务器需要反馈给客户端的信息
服务监听与请求处理过程
net.Listen("tcp", addr)
,监控我们设置的端口。监控端口之后,调用 srv.Serve(net.Listener)
函数,处理接收客户端的请求信息。首先通过
分配相应的函数处理请求handler = DefaultServeMux。DefaultServeMux
是一个路由器,它用来匹配http.HandleFunc("/", sayhelloName)
作用是注册了请求

自定义路由实现
定义的类型实现
package main
import (
"fmt"
"log"
"net/http"
)
type MyMux struct {}
func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
sayhelloName(w, r)
return
}
http.NotFound(w, r)
return
}
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println("path:", r.URL.Path)
fmt.Fprintf(w, "hello go")
}
func main() {
mux := &MyMux{}
err := http.ListenAndServe(":9090", mux)
if err != nil {
log.Fatal("ListenAndServer: ", err)
}
}