How Http Server Add Http Basic Auth In Golang

My computer develop environment

1
2
3
4
5
6
7
$ sw_vers 
ProductName: Mac OS X
ProductVersion: 10.12.6
BuildVersion: 16G29

$ go version
go version go1.8.3 darwin/amd64

How to add bash auth to filter the request in web server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main

import (
"bytes"
"io"
"net/http"
"strings"
"encoding/base64"
)

type requestFunc func(http.ResponseWriter, *http.Request)

func BasicAuth(execFunc requestFunc, username, password []byte) requestFunc {

return func(w http.ResponseWriter, r *http.Request) {

basicAuthPrefix := "Basic "

// get the request header
auth := r.Header.Get("Authorization")

// if request with http basic auth
if strings.HasPrefix(auth, basicAuthPrefix) {

// decode it
payload, err := base64.StdEncoding.DecodeString(
auth[len(basicAuthPrefix):],
)

if err == nil {

pair := bytes.SplitN(payload, []byte(":"), 2)

if len(pair) == 2 && bytes.Equal(pair[0], username) &&
bytes.Equal(pair[1], password) {

execFunc(w, r)
return
}
}
}

// if auth failed, restricted other value
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
// return 401 status code
w.WriteHeader(http.StatusUnauthorized)
}
}

func secretRequest(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "You got 1 million!!!\n")
}

func main() {

username := []byte("admin")
password := []byte("password")

http.HandleFunc("/", BasicAuth(secretRequest, username, password))
http.ListenAndServe(":8000", nil)
}
Share