Skip to content

Instantly share code, notes, and snippets.

@klrkdekira
Created October 23, 2016 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klrkdekira/e38458be5ba781d1243a782dd6008f4c to your computer and use it in GitHub Desktop.
Save klrkdekira/e38458be5ba781d1243a782dd6008f4c to your computer and use it in GitHub Desktop.
Golang net/http HandlerFunc demo
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
func sayHelloHandlerFunc(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func protectThis(db map[string]string, f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
username, password, found := r.BasicAuth()
if !found {
w.Write([]byte("Access denied!"))
return
}
// check db
matchPW, found := db[username]
if !found {
w.Write([]byte("Access denied!"))
return
}
if matchPW != password {
w.Write([]byte("Access denied!"))
return
}
// proceed to protected resource
f(w, r)
}
}
func main() {
mainHandler := http.NewServeMux()
// unprotected
mainHandler.HandleFunc("/free", sayHelloHandlerFunc)
// protected resource
// dummy userdb
db := map[string]string{
"doctor": "who",
}
mainHandler.HandleFunc("/protected", protectThis(db, sayHelloHandlerFunc))
go func() {
if err := http.ListenAndServe(":8080", mainHandler); err != nil {
panic(err)
}
}()
fmt.Println("Started web server")
// give the server sometime to start
time.Sleep(time.Millisecond)
// test starts here
// request for /free
req, err := http.NewRequest("GET", "http://127.0.0.1:8080/free", nil)
if err != nil {
panic(err)
}
req.Close = true
fmt.Println("Calling /free")
lookup(req)
// request for /protected
req, err = http.NewRequest("GET", "http://127.0.0.1:8080/protected", nil)
if err != nil {
panic(err)
}
req.Close = true
fmt.Println("Calling /protected without auth")
lookup(req)
fmt.Println("Calling /protected with wrong credential")
req.SetBasicAuth("foo", "bar")
lookup(req)
fmt.Println("Calling /protected with correct credential")
req.SetBasicAuth("doctor", "who")
lookup(req)
}
// since this is a test, all errors will result in panic
func lookup(r *http.Request) {
resp, err := http.DefaultClient.Do(r)
if err != nil {
panic(err)
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("Received response,\n%s\n===\n", b)
}
Started web server
Calling /free
Received response,
Hello, World!
===
Calling /protected without auth
Received response,
Access denied!
===
Calling /protected with wrong credential
Received response,
Access denied!
===
Calling /protected with correct credential
Received response,
Hello, World!
===
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment