dongta5747 2018-07-12 17:12
浏览 97
已采纳

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

I have two tasks I need to fulfill when the "/" pattern is present in a request, both of which require using http handlers.

They are:

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

The index handler checks for proper authentication to access a webpage, and the handler above it serves up a directory (in the future I will make it to where it will only serve the directory if authentication requirements are met).

Is it possible to have two handlers for the same pattern (currently gives error)? If not, is there any other way to check authentication and serve up the directory with a single handler?

  • 写回答

2条回答 默认 最新

  • 普通网友 2018-07-13 16:15
    关注

    I'm going to have to retract my previous answer acceptance because this is much closer to what I was looking for (have to import github.com/abbot/go-http-auth):

    package main
    
    import (
        "fmt"
        "net/http"
        auth "github.com/abbot/go-http-auth"
    )
    
    func Secret(user, realm string) string {
        if user == "john" {
            // password is "hello"
            return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1"
        }
        return ""
    }
    
    func main() {
        fmt.Println("-----> Starting HTTP server...")
    
    authenticator := auth.NewBasicAuthenticator("secret.com", Secret)
    http.HandleFunc("/", authenticator.Wrap(func(res http.ResponseWriter, req *auth.AuthenticatedRequest) {
        http.FileServer(http.Dir(".")).ServeHTTP(res, &req.Request)
    }))
    
    http.ListenAndServe(":5042", nil)
    }
    

    This method is much easier to follow and more intutive (for me at least).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错