Created
January 10, 2023 04:59
-
-
Save danstn/614b59e325f65eabebcda42a2a272a18 to your computer and use it in GitHub Desktop.
Simple Go 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 ( | |
"fmt" | |
"log" | |
"net/http" | |
"net/http/httputil" | |
"strings" | |
) | |
// Reverse proxy: | |
// | |
// localhost:8080/foo -> localhost:8081/ | |
// localhost:8080/bar -> localhost:8082/ | |
func main() { | |
log.Println("[main] starting application") | |
fooAddr := "127.0.0.1:8081" | |
go startServerFoo(fooAddr) | |
barAddr := "127.0.0.1:8082" | |
go startServerBar(barAddr) | |
// custom proxy with a director routing based on the 1st part of the path | |
proxy := &httputil.ReverseProxy{ | |
Director: func(req *http.Request) { | |
log.Printf("[director] req: %+v", req.URL) | |
// get first part | |
path := strings.TrimPrefix(req.URL.Path, "/") | |
parts := strings.SplitN(path, "/", 2) | |
firstPart := parts[0] | |
req.URL.Scheme = "http" | |
switch firstPart { | |
case "foo": | |
req.URL.Host = fooAddr | |
case "bar": | |
req.URL.Host = barAddr | |
} | |
}, | |
} | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("[proxy] handling request: %s", r.URL) | |
//proxy.ServeHTTP(w, r) | |
}) | |
// start reverse proxy server | |
if err := http.ListenAndServe(":8080", nil); err != nil { | |
panic(err) | |
} | |
} | |
func startServerFoo(addr string) { | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("[foo] received a request: %v", r) | |
fmt.Fprintf(w, "foo says hi!") | |
}) | |
log.Printf("[foo] listening on: %s", addr) | |
http.ListenAndServe(addr, mux) | |
} | |
func startServerBar(addr string) { | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("[bar] received a request: %v", r) | |
fmt.Fprintf(w, "bar says hi!") | |
}) | |
log.Printf("[bar] listening on: %s", addr) | |
http.ListenAndServe(addr, mux) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment