O'Reilly logo

Go Web Development Cookbook by Arpit Aggarwal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required