gpt4 book ai didi

http - 如何将多个处理程序分配给同一个 uri?

转载 作者:IT王子 更新时间:2023-10-29 01:53:57 26 4
gpt4 key购买 nike

当请求中出现“/”模式时,我有两个任务需要完成,这两个任务都需要使用 http 处理程序。

它们是:

http.Handle("/", http.FileServer(http.Dir("dtfw-tool/build/")))
http.HandleFunc("/", index)

索引处理程序检查正确的身份验证以访问网页,它上面的处理程序提供一个目录(将来我会把它变成只在满足身份验证要求时才提供目录的地方)。

是否可以为同一个模式设置两个处理程序(当前给出错误)?如果没有,是否有任何其他方法来检查身份验证并使用单个处理程序提供目录?

最佳答案

创建一个中间件来验证用户并将处理程序返回到主 Handle ,它将包装您的最终处理程序

package main

import (
"log"
"net/http"
)

func main() {
finalHandler := http.HandlerFunc(final)
http.Handle("/", authentication(finalHandler))
http.ListenAndServe(":3000", nil)
}

func authentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing authentication")
next.ServeHTTP(w, r) //`next.ServeHTTP(w, r)` will forward the request and response to next handler.
})
}

func final(w http.ResponseWriter, r *http.Request) {
log.Println("Executing finalHandler")
w.Write([]byte("User authenticated"))
}

在 Golang 中 HanlderFunc 用于返回 hanlder,它将成为一个中间件来包装 main 函数:

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

server.go 的源代码中也有定义。

Playground Example

关于http - 如何将多个处理程序分配给同一个 uri?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51311182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com