如何将gorilla mux与http.TimeoutHandler一起使用

编程入门 行业动态 更新时间:2024-10-10 06:20:10
本文介绍了如何将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:

  • 我通过创建一个新的路由器, gorillaMux:= mux.NewRouter()
  • 通过像> gorillaMux.HandleFunc(/,rootHandler) code>
  • 我通过 server:=& http.Server {Addr::1234}创建服务器和 server.ListenAndServe()
  • I create a new Router by gorillaMux := mux.NewRouter()
  • add my routes by calls like gorillaMux.HandleFunc("/", rootHandler)
  • 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/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一起使用

    本文发布于:2023-11-25 16:56:22,感谢您对本站的认可!
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:如何将   gorilla   mux   http   TimeoutHandler

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!