Last active
August 29, 2015 14:05
-
-
Save jakecoffman/66ce8839b37e40e75a53 to your computer and use it in GitHub Desktop.
Golang reverse proxy.
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 ( | |
"log" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
) | |
func main() { | |
// This is the server to proxy | |
remote, err := url.Parse("http://localhost:4000") | |
if err != nil { | |
log.Fatal(err) | |
} | |
proxy := httputil.NewSingleHostReverseProxy(remote) | |
// wrap the reverse proxy in a custom handler below | |
http.HandleFunc("/", handler(proxy)) | |
// serve on port 1234 forever | |
log.Fatal(http.ListenAndServe("localhost:1234", nil)) | |
} | |
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) { | |
// returns a function that satisfies the http.HandlerFunc interface | |
return func(w http.ResponseWriter, r *http.Request) { | |
// set the user name before performing the proxy | |
r.Header.Set("REMOTE_USER", "Bob") | |
p.ServeHTTP(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment