Golang net/http.Request.BasicAuth() function example
package net/http
Golang net/http.Request.BasicAuth() function usage example
package main
import (
"fmt"
"net/http"
"strings"
"encoding/base64"
)
var username = []byte("hello")
var password = []byte("password")
func BasicAuth(w http.ResponseWriter, r *http.Request, user, pass []byte) bool {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
return false
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return false
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return false
}
return pair[0] == string(user) && pair[1] == string(pass)
}
func home(w http.ResponseWriter, r *http.Request) {
// pass from global variables
if BasicAuth(w, r, username, password) {
w.Write([]byte("Welcome to the Protected Page!!"))
return
}
w.Header().Set("WWW-Authenticate", `Basic realm="Beware! Protected REALM! "`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
// ---- HERE ! -----
username, password, ok := r.BasicAuth()
fmt.Println("username : ", username)
fmt.Println("password : ", password)
fmt.Println("ok : ", ok)
}
func main() {
http.HandleFunc("/", home)
http.ListenAndServe(":8080", nil)
}
Sample output :
username :
password :
ok : false
after entering username and password
username : username
password : password
ok : true
References :
http://golang.org/pkg/net/http/#Request.BasicAuth
https://www.socketloop.com/tutorials/golang-basic-authentication-with-htpasswd-file
Advertisement
Something interesting
Tutorials
+16.3k Golang : convert string or integer to big.Int type
+10.3k Golang : Detect number of faces or vehicles in a photo
+6.1k Golang : Grab news article text and use NLP to get each paragraph's sentences
+12.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+5.7k List of Golang XML tutorials
+9.7k PHP : Get coordinates latitude/longitude from string
+13.5k Facebook PHP getUser() returns 0
+20.7k Golang : Read directory content with os.Open
+12.7k Golang : Pass database connection to function called from another package and HTTP Handler
+14.9k Golang : Submit web forms without browser by http.PostForm example
+8.3k Golang : Count leading or ending zeros(any item of interest) example
+8.3k Golang : Configure Apache and NGINX to access your Go service example