【问题标题】:goji/httpauth - Cannot use with the standard Golang 'net/http' librarygoji/httpauth - 不能与标准 Golang 'net/http' 库一起使用
【发布时间】:2017-10-28 23:29:26
【问题描述】:

代码

package main

import (
        "fmt"
        "log"
        "net/http"
        "github.com/goji/httpauth"
)


func rootHandler(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain")
        w.WriteHeader(http.StatusOK)

        data := "TEST"

        w.Header().Set("Content-Length", fmt.Sprint(len(data)))
        fmt.Fprint(w, string(data))
}

func main() {
        r:=http.HandlerFunc(rootHandler)
        http.HandleFunc("/", httpauth.SimpleBasicAuth("dave", "somepassword")(r))
        log.Fatal(http.ListenAndServe(":8080", nil))
}

返回

:!go build test.go
# command-line-arguments
./test.go:23:71: cannot use httpauth.SimpleBasicAuth("dave", "somepassword")(r) (type http.Handler) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc

我做错了什么?我是 Go 新手,不明白为什么示例 here 不完整且不包含 YourHandler 函数。

【问题讨论】:

  • 旁白:w.Header().Set() 在w.WriteHeader() 之后无效。以防万一这也在你的实际程序中。

标签: go goji


【解决方案1】:

在我的头撞到众所周知的墙上后,我想通了。

使用http.Handle,而不是http.HandleFunc! :)

所以使用main 函数作为

func main() {
        r:=http.HandlerFunc(rootHandler)
        http.Handle("/", httpauth.SimpleBasicAuth("dave", "somepassword")(r))
        log.Fatal(http.ListenAndServe(":8080", nil))
}

你有一个完整的使用 net/http 的 httpauth 工作示例!

This answer 对内部运作也有非常好的概述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    相关资源
    最近更新 更多