In this recipe, we are going to update the HTTP server we created in the previous recipe by adding a BasicAuth function and modifying the HandleFunc to call it. Perform the following steps:
- Create http-server-basic-authentication.go and copy the following content:
package mainimport ( "crypto/subtle" "fmt" "log" "net/http")const ( CONN_HOST = "localhost" CONN_PORT = "8080" ADMIN_USER = "admin" ADMIN_PASSWORD = "admin")func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!")}func BasicAuth(handler http.HandlerFunc, realm string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(ADMIN_USER)) ...