中间件在没有指定挂载路径的情况下,会在每个请求中执行。

huangapple go评论95阅读模式
英文:

middleware gets executed for every request without specify a mount path

问题

在Go中,可以使用net/http包来实现类似的功能。下面是一个示例代码:

package main

import (
	"fmt"
	"net/http"
	"time"
)

func main() {
	// 创建一个处理器函数
	handler := func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("Time:", time.Now())
		// 继续处理请求
	}

	// 创建一个服务器并注册处理器函数
	server := http.Server{
		Addr:    ":8080",
		Handler: http.HandlerFunc(handler),
	}

	// 启动服务器
	server.ListenAndServe()
}

这段代码创建了一个简单的HTTP服务器,它会在每个请求到达时打印当前时间。你可以根据自己的需求修改处理器函数的逻辑。

英文:

Node.js Express can insert a middleware with no mount path, and it gets executed for every request. Is there a way to accomplish that in GO?

var app = express();

// a middleware with no mount path; gets executed for every request to the app
app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

答案1

得分: 2

这是一个使用Go的net/http库的基本示例:

func main() {
   r := http.NewServeMux()
   r.HandleFunc("/some-route", SomeHandler)
 
   // 使用一个类似于下面的函数包装你的*ServeMux
   // func SomeMiddleware(h http.Handler) http.Handler   
   http.ListenAndServe("/", YourMiddleware(r))
}

中间件可能是这样的:

func YourMiddleware(h http.Handler) http.Handler {
   fn := func(w http.ResponseWriter, r *http.Request) {
       // 对响应进行处理
       w.Header().Set("Server", "Probably Go")
       // 调用下一个处理程序
       h.ServeHTTP(w, r)
   }
   
   // 类型转换我们的函数,以满足http.Handler接口
   return http.HandlerFunc(fn)
}

如果你有很多中间件需要链接,像alice这样的包可以简化代码,这样你就不需要像Wrapping(AllOf(YourMiddleware(r))))那样。你也可以编写自己的辅助函数:

func use(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
    for _, m := range middleware {
        h = m(h)
    }
    return h
}

// 示例用法:
defaultRouter := use(r, handlers.LoggingHandler, csrf.Protect(key), CORSMiddleware)
http.ListenAndServe(":8000", defaultRouter)
英文:

Here's a basic example with Go's net/http:

func main() {
   r := http.NewServeMux()
   r.HandleFunc("/some-route", SomeHandler)
 
   // Wrap your *ServeMux with a function that looks like
   // func SomeMiddleware(h http.Handler) http.Handler   
   http.ListenAndServe("/", YourMiddleware(r))
}

Middleware might be something like this:

func YourMiddleware(h http.Handler) http.Handler {
   fn := func(w http.ResponseWriter, r *http.Request) {
       // Do something with the response
       w.Header().Set("Server", "Probably Go")
       // Call the next handler
       h.ServeHTTP(w, r)
   }
   
   // Type-convert our function so that it
   // satisfies the http.Handler interface
   return http.HandlerFunc(fn)
}

If you have a lot of middleware you want to chain, a package like alice can simplify it so you're not Wrapping(AllOf(YourMiddleware(r)))) like that. You could also write your own helper -

func use(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
    for _, m := range middleware {
        h = m(h)
    }
    return h
}

// Example usage:
defaultRouter := use(r, handlers.LoggingHandler, csrf.Protect(key), CORSMiddleware)
http.ListenAndServe(":8000", defaultRouter)

huangapple
  • 本文由 发表于 2015年11月12日 10:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/33663352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定