4

在用 go 编写的 HTTP 服务器中,我使用gorilla/mux进行路由,
我想使用http.TimeoutHandler(和/或其他“中间件”),但我不明白我可以在哪里安装它们。

说清楚:

  1. 我创建了一个新的路由器gorillaMux := mux.NewRouter()
  2. 通过像这样的电话添加我的路线gorillaMux.HandleFunc("/", rootHandler)
  3. server := &http.Server{Addr:":1234"}我通过and创建服务器server.ListenAndServe()

我可以在哪里插入http.TimeoutHandler或任何其他中间件?

4

2 回答 2

11

您可以这样做:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
    "time"
)

func rootHandler(w http.ResponseWriter, r *http.Request) {
    time.Sleep(5 * time.Second)
    fmt.Fprintf(w, "Hello!")
}

func main() {
    mux := mux.NewRouter()
    mux.HandleFunc("/", rootHandler)

    muxWithMiddlewares := http.TimeoutHandler(mux, time.Second*3, "Timeout!")

    http.ListenAndServe(":8080", muxWithMiddlewares)
}

如果您有多个 HTTP 处理程序,则可以将它们堆叠起来:

// this is quite synthetic and ugly example, but it illustrates how Handlers works
muxWithMiddlewares := http.StripPrefix("/api", http.TimeoutHandler(mux, time.Second*3, "Timeout!"))
于 2013-10-29T13:44:33.863 回答
1

此解决方案不回答使用 TimeoutHandler。我在这里发布了这个,以防有人想要细粒度地控制他们的服务器超时。如果需要,此替代方案将允许定义 IdleTimeout 和 RequestHeaderTimeout。在这个例子中,我同时使用了 gorilla/mux 和 gorilla/handlers。希望能帮助到你。

// ReadTimeout is a timing constraint on the client http request imposed by the server from the moment
// of initial connection up to the time the entire request body has been read.
// [Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]

// WriteTimeout is a time limit imposed on client connecting to the server via http from the
// time the server has completed reading the request header up to the time it has finished writing the response.
// [Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]

func main() {
    mux := router.EpicMux()

    srv := &http.Server{
        Handler:      handlers.LoggingHandler(os.Stdout, mux),
        Addr:         "localhost:8080",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    log.Fatal(srv.ListenAndServe())
}

func EpicMux() http.Handler {
    r := mux.NewRouter()
    r.HandleFunc("/", BaseURLRouter).Methods(http.MethodGet)
    // create the subroutes for v1 and v2
    v1 := r.PathPrefix("api/v1").Subrouter()
    // register handlers to appropriate version
    v1.HandleFunc("/person", PersonHandlerV1).Methods(http.MethodPost)

    v2 := r.PathPrefix("api/v2").Subrouter()
    v2.HandleFunc("/person",    PersonHandlerV2).Methods(http.MethodPost)
    return r
}
于 2017-12-01T23:42:48.833 回答