0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61
  • Aside: `w.Header().Set()` after `w.WriteHeader()` has no effect. Just in case that's also in your real program. – Peter Oct 28 '17 at 14:33

1 Answers1

0

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.

Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61