亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 http.TimeoutHandler 中使用 gorilla mux

如何在 http.TimeoutHandler 中使用 gorilla mux

Go
森林海 2021-06-28 15:31:07
在用 go 編寫的 HTTP 服務器中,我使用gorilla/mux進行路由,我想使用http.TimeoutHandler(和/或其他“中間件”),但我不明白我可以在哪里安裝它們。要說清楚:我創建了一個新的路由器 gorillaMux := mux.NewRouter()通過調用添加我的路線 gorillaMux.HandleFunc("/", rootHandler)我通過server := &http.Server{Addr:":1234"}和創建服務器server.ListenAndServe()我可以在哪里插入http.TimeoutHandler或任何其他中間件?
查看完整描述

2 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

此解決方案不回答使用 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

}


查看完整回答
反對 回復 2021-07-05
  • 2 回答
  • 0 關注
  • 265 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號