TimeoutHandler一起使用

TimeoutHandler一起使用

本文介绍了如何将gorilla mux与http.TimeoutHandler一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在go中写入的HTTP服务器中,我使用进行路由, >
我想使用 http.TimeoutHandler (和/或其他中间件),但我无法理解我可以在哪里适合它们。

In an HTTP server written in go, I use gorilla/mux for routing,
I want to use http.TimeoutHandler (and/or other "middleware") but I can't understand where I can fit them.

为了说清楚:

To make it clear:


  1. 我通过创建一个新的路由器, gorillaMux:= mux.NewRouter()

  2. 通过像> gorillaMux.HandleFunc(/,rootHandler) code>

  3. 我通过 server:=& http.Server {Addr::1234}创建服务器 server.ListenAndServe()

  1. I create a new Router by gorillaMux := mux.NewRouter()
  2. add my routes by calls like gorillaMux.HandleFunc("/", rootHandler)
  3. I create the server by server := &http.Server{Addr:":1234"} and server.ListenAndServe()

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

Where can I insert the http.TimeoutHandler or any other middleware for that matter?

推荐答案

可以这样做:

Here is how you can do this:

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处理程序,您可以将它们堆叠在一起:

If you have more than one HTTP handler, you can stack them up:

// this is quite synthetic and ugly example, but it illustrates how Handlers works
muxWithMiddlewares := http.StripPrefix("/api", http.TimeoutHandler(mux, time.Second*3, "Timeout!"))

这篇关于如何将gorilla mux与http.TimeoutHandler一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:31