如何在go中为同一个uri分配多个处理程序?

And*_*rew 3 http handler go

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

他们是:

http.Handle("/", http.FileServer(http.Dir("dtfw-tool/build/")))
http.HandleFunc("/", index)
Run Code Online (Sandbox Code Playgroud)

索引处理程序检查访问网页的正确身份验证,并且它上面的处理程序提供一个目录(将来,如果满足身份验证要求,我将使它只提供目录服务)。

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

Him*_*shu 6

创建一个中间件来验证用户并将处理程序返回给 main 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"))
}
Run Code Online (Sandbox Code Playgroud)

在 GolangHanlderFunc中用于返回处理程序,处理程序将成为包装 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)
Run Code Online (Sandbox Code Playgroud)

它也在源代码中定义为 server.go

游乐场示例