How to do it...

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:

  1. 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)) ...

Get Go Web Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.