Skip to content

Instantly share code, notes, and snippets.

@benjic
Created April 13, 2017 23:19
Show Gist options
  • Save benjic/eb89ef9c52259fb31d5f0bf04a637408 to your computer and use it in GitHub Desktop.
Save benjic/eb89ef9c52259fb31d5f0bf04a637408 to your computer and use it in GitHub Desktop.
GH Authentication Proxy
package main
import (
"encoding/base64"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
)
const (
localHost = `127.0.0.1:8000`
remoteHost = `https://api.github.com`
tokenEnvName = `GH_TOKEN`
usernameEnvName = `GH_USERNAME`
)
func main() {
ghURL, err := url.Parse(remoteHost)
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(ghURL)
director, err := getDirector(proxy.Director)
if err != nil {
panic(err)
}
proxy.Director = director
fmt.Printf("Proxying requests to %s to %s\n", localHost, remoteHost)
if err := http.ListenAndServe(localHost, proxy); err != nil {
panic(err)
}
}
func getDirector(defaultDirector func(*http.Request)) (func(*http.Request), error) {
accessToken := os.Getenv(tokenEnvName)
username := os.Getenv(usernameEnvName)
if accessToken == "" || username == "" {
fmt.Fprintf(os.Stderr, "Could not detect %s value; Requests will be unauthenticated.\n", tokenEnvName)
}
return func(req *http.Request) {
defaultDirector(req)
req.Host = "api.github.com"
fmt.Printf("Proxying request: %s\n", req.URL)
if accessToken != "" && username != "" {
token := base64.StdEncoding.EncodeToString([]byte(username + ":" + accessToken))
req.Header.Set("Authorization", "Basic "+token)
}
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment