Skip to content

Instantly share code, notes, and snippets.

@steffen25
Last active November 19, 2017 20:39
Show Gist options
  • Save steffen25/50a74a05966bdfa394fe62aad0788071 to your computer and use it in GitHub Desktop.
Save steffen25/50a74a05966bdfa394fe62aad0788071 to your computer and use it in GitHub Desktop.
basic auth go
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"crypto/subtle"
)
func main() {
http.HandleFunc("/mailchimp", basicAuth(mailchimpHandler))
log.Fatal(http.ListenAndServe(":8000", nil))
}
func mailchimpHandler(w http.ResponseWriter, r *http.Request) {
response, err := http.Get("https://us14.api.mailchimp.com/3.0/reports/")
if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Fprint(w, string(responseData))
}
func basicAuth(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var authed int8
// Show popup I dont know if you want this
//w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
username, password, authOK := r.BasicAuth()
// Prevent timing attacks
// Change "username" for your needs
if subtle.ConstantTimeCompare([]byte("username"), []byte(username)) == 1 {
authed = authed | 1
}
// Change "password" for your needs
if subtle.ConstantTimeCompare([]byte("password"), []byte(password)) == 1 {
authed = authed | 2
}
if authed != 3 {
http.Error(w, "Not authorized", 401)
return
}
if !authOK {
http.Error(w, "Not authorized", 401)
return
}
h.ServeHTTP(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment