目前知道gin是基于net/http进一步封装,来看下net/http是怎样写web的
package main
import (
"fmt"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello World")
}
func main() {
http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil)
}
首先,调用http.HandleFunc("/", index)
注册路径处理函数,这里将路径/
的处理函数设置为index
。处理函数的类型必须是:、
func (http.ResponseWriter, *http.Request)
其中*http.Request
表示 HTTP 请求对象,该对象包含请求的所有信息,如 URL、首部、表单内容、请求的其他内容等。
http.ResponseWriter
是一个接口类型:
// net/http/server.go
type ResponseWriter interface {
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
}
用于向客户端发送响应,实现了ResponseWriter
接口的类型显然也实现了io.Writer
接口。所以在处理函数index
中,可以调用fmt.Fprintln()
向ResponseWriter
写入响应信息。
net/http
包中HandleFunc()
函数的源码:
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}
接调用了一个名为DefaultServeMux
对象的HandleFunc()
方法。DefaultServeMux
是ServeMux
类型的实例:
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
hosts bool // whether any patterns contain hostnames
}
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
像这种提供默认类型实例的用法在 Go 语言的各个库中非常常见,在默认参数就已经足够的场景中使用默认实现很方便。ServeMux
保存了注册的所有路径和处理函数的对应关系。ServeMux.HandleFunc()
方法如下:
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
mux.Handle(pattern, HandlerFunc(handler))
}
这里将处理函数handler
转为HandlerFunc
类型,然后调用ServeMux.Handle()
方法注册。注意这里的HandlerFunc(handler)
是类型转换,而非函数调用,类型HandlerFunc
的定义如下:
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
HandlerFunc
实际上是以函数类型func(ResponseWriter, *Request)
为底层类型,为HandlerFunc
类型定义了方法ServeHTTP
mux.Handle(pattern, HandlerFunc(handler)) 调用了func (mux *ServeMux) Handle(pattern string, handler Handler)
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()
if _, exist := mux.m[pattern]; exist {
panic("http: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
e := muxEntry{h: handler, pattern: pattern}
mux.m[pattern] = e
if pattern[len(pattern)-1] == '/' {
mux.es = appendSorted(mux.es, e)
}
if pattern[0] != '/' {
mux.hosts = true
}
}
也就是:
mux.Handle(pattern, HandlerFunc(handler))------>
func (mux *ServeMux) Handle(pattern string, handler Handler)
HandlerFunc(handler)---
--->Handler
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
标签:http,pattern,mux,handler,func,gin,net,ResponseWriter From: https://www.cnblogs.com/codestack/p/17977169