golang http 服務器的接口梳理

golang http 服務器的接口梳理

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

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的結構體,所以控制邏輯能夠靈活些。
api

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()
}
相關文章
相關標籤/搜索