本文来源于: https://gobea.cn/blog/detail/15zqpwrq.html
最简略的http服务
golang
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world")
})
http.ListenAndServe(":8899", nil)
}
http://127.0.0.1:8899hello world
http服务
golang
HandlerHandlerServeHTTPServeHTTPfunc(w http.ResponseWriter, r *http.Request)http.HandlerFuncHandlerServeMuxpatternHandlerpatternHandlerHandlerServeHTTP
handlerhandlerServeHTTPHandlerFuncServeHTTPhandler
handler对象
// Handler接口
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
// HandlerFunc实现了Handler接口
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
handlerhandlerServeHTTPHandlerServeHTTP
func(w http.ResponseWriter, r *http.Requests)HandlerFuncHandlerHandlerFuncHandlerFuncServeHTTPServeHTTP
注册路由ServeMux
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
hosts bool
}
type muxEntry struct {
explicit bool
h Handler
pattern string
}
// ServeMux也领有ServeHTTP办法,也就说ServeMux实现了Handler接口,即ServeMuX其实也是一个Handler对象,不过ServeMux的ServeHTTP办法不是用来解决request和respone,而是用来找到路由注册的handler
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
if r.RequestURI == "*" {
if r.ProtoAtLeast(1, 1) {
w.Header().Set("Connection", "close")
}
w.WriteHeader(StatusBadRequest)
return
}
h, _ := mux.Handler(r)
h.ServeHTTP(w, r)
}
ServeMux.mpatternHandlerServeMuxServeHTTPServeMuxHandlerServeMuXHandler
package main
import (
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world")
})
mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world")
})
http.ListenAndServe(":8899", mux)
}
Server
http.ListenAndServe(":8899",mux)
// 等价于
serv := &http.Server{
Addr: ":8899",
Handler: mux,
}
serv.ListenAndServe()
http.ListenAndServe源码如下:
func ListenAndServe(addr string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
起源
- https://gobea.cn/blog/detail/…
参考
- https://www.jianshu.com/p/be3…