Reputation: 7357
The code
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))
}
returns
:!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
What am I doing wrong? I'm new to Go and don't understand why the example here is incomplete and doesn't include a YourHandler
function.
Upvotes: 0
Views: 116
Reputation: 7357
I figured it out after much banging my head against the proverbial wall.
Use http.Handle
, not http.HandleFunc
! :)
So with the main
function as
func main() {
r:=http.HandlerFunc(rootHandler)
http.Handle("/", httpauth.SimpleBasicAuth("dave", "somepassword")(r))
log.Fatal(http.ListenAndServe(":8080", nil))
}
You have a complete working example of httpauth with net/http!
This answer has a really great overview of the inner workings as well.
Upvotes: 0