golang http 服務器的接口梳理


golang http 服務器的接口梳理

Golang構建HTTP服務(二)--- Handler,ServeMux與中間件

Hanlde和HandleFunc以及Handler, HandlerFunc
func Handle(pattern string, handler Handler)
// Handle 函數將pattern和對應的handler注冊進DefaultServeMux
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
// HandleFunc registers the handler function for the given pattern in the DefaultServeMux
// Handler
// 
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}
// HandlerFunc能夠將一個普通的處理函數轉化為Handler
type HandlerFunc func(ResponseWriter, *Request)

HandleFunc僅接受一個func為參數,相對於簡潔些。Handle則需要傳入一個帶有ServeHTTP的結構體,因此控制邏輯可以靈活些。

Handle的例子
package main

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

type countHandler struct {
    mu  sync.Mutex // guards n
    n   int
}

func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    h.mu.Lock()
    defer h.mu.Unlock()
    h.n++
    fmt.Fprintf(w, "count is %d\n", h.n)
}

func main() {
    http.Handle("/count", new(countHandler))
    log.Fatal(http.ListenAndServe(":8080", nil))
}
HandleFunc的例子

h1 := func(w http.ResponseWriter, _ *http.Request) {
    io.WriteString(w, "Hello from a HandleFunc #1!\n")
}
h2 := func(w http.ResponseWriter, _ *http.Request) {
    io.WriteString(w, "Hello from a HandleFunc #2!\n")
}

http.HandleFunc("/", h1)
http.HandleFunc("/endpoint", h2)

log.Fatal(http.ListenAndServe(":8080", nil))

##### ListenAndServe ``` // 監聽TCP然后調用handler對應的Serve去處理請求。handler默認為nil,則使用DefaultServeMux func ListenAndServe(addr string, handler Handler) error ``` ##### ServeMux 路由調度器,根據請求url調用handler去處理。實現了Handle,HandleFunc方法。 ServeMux實現了ServeHTTP因此也是一個Handler接口 ``` // 新建 func NewServeMux() *ServeMux // 方法 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) func (mux *ServeMux) Handle(pattern string, handler Handler) func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) // mux := http.NewServeMux() mux.Handle("/api/", apiHandler{}) mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { // The "/" pattern matches everything, so we need to check // that we're at the root here. if req.URL.Path != "/" { http.NotFound(w, req) return } fmt.Fprintf(w, "Welcome to the home page!") }) ``` ##### Server 類型 ``` type Server struct { Addr string // TCP address to listen on, ":http" if empty Handler Handler // handler to invoke, http.DefaultServeMux if nil TLSConfig *tls.Config ReadTimeout time.Duration ReadHeaderTimeout time.Duration WriteTimeout time.Duration IdleTimeout time.Duration MaxHeaderBytes int TLSNextProto map[string]func(*Server, *tls.Conn, Handler) ConnState func(net.Conn, ConnState) ErrorLog *log.Logger // contains filtered or unexported fields } // 方法 func (srv *Server) Close() error func (srv *Server) ListenAndServe() error func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error func (srv *Server) RegisterOnShutdown(f func()) func (srv *Server) Serve(l net.Listener) error func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error func (srv *Server) SetKeepAlivesEnabled(v bool) func (srv *Server) Shutdown(ctx context.Context) error ``` 可以通過Server類型來改變默認的Server配置,如改變監聽端口等。 ``` func main(){ http.HandleFunc("/", index)
server := &http.Server{
    Addr: ":8000",
    ReadTimeout: 60 * time.Second,
    WriteTimeout: 60 * time.Second,
}
server.ListenAndServe()

}
// 自定義的serverMux對象也可以傳到server對象中。
func main() {

mux := http.NewServeMux()
mux.HandleFunc("/", index)

server := &http.Server{
    Addr: ":8000",
    ReadTimeout: 60 * time.Second,
    WriteTimeout: 60 * time.Second,
    Handler: mux,
}
server.ListenAndServe()

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM