Created
October 26, 2019 20:43
-
-
Save srgrn/34a9d650093668cee9b343f44f77530b to your computer and use it in GitHub Desktop.
a simple proxy to convert basic auth to token auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"strings" | |
) | |
type ReverseProxy struct { | |
proxy *httputil.ReverseProxy | |
} | |
func NewReverseProxy(target string) (proxy *ReverseProxy) { | |
p := ReverseProxy{} | |
url, _ := url.Parse(target) | |
p.proxy = httputil.NewSingleHostReverseProxy(url) | |
return &p | |
} | |
func (p *ReverseProxy) handle(w http.ResponseWriter, r *http.Request) { | |
if r.Method == http.MethodOptions { | |
fmt.Fprintf(w, "%s", "Goodbye\n") | |
return | |
} | |
auth := r.Header.Get("Authorization") | |
if auth == "" { | |
w.WriteHeader(http.StatusNotAcceptable) | |
fmt.Fprintf(w, "Error with auth") | |
return | |
} | |
if strings.HasPrefix(auth, "Basic") { | |
fmt.Println("Using basic auth") | |
fmt.Println("Here be token") | |
token := "1234567890" | |
r.Header.Set("Authorization", "Bearer "+token) | |
} | |
w.Header().Set("X-GoProxy", "GoProxy") | |
p.proxy.ServeHTTP(w, r) | |
} | |
func main() { | |
const ( | |
defaultPort = "9090" | |
defaultPortUsage = "default server port, ':9090'" | |
defaultTarget = "https://postb.in/1572119126327-6632650287356" | |
defaultTargetUsage = "default redirect url, 'https://postb.in/1572119126327-6632650287356'" | |
) | |
// flags | |
port := flag.String("port", defaultPort, defaultPortUsage) | |
redirecturl := flag.String("url", defaultTarget, defaultTargetUsage) | |
flag.Parse() | |
fmt.Println("server will run on :", *port) | |
fmt.Println("redirecting to :", *redirecturl) | |
// proxy | |
proxy := NewReverseProxy(*redirecturl) | |
// server redirection | |
http.HandleFunc("/", proxy.handle) | |
log.Fatal(http.ListenAndServe(":"+*port, nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment