Created
January 20, 2021 10:15
-
-
Save iOliverNguyen/be67c041db23139553dd1b60d1484f5b to your computer and use it in GitHub Desktop.
A simple http proxy in Go
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" | |
"io" | |
"net/http" | |
"time" | |
) | |
var client = http.Client{Timeout: 5 * time.Second} | |
func proxy(scheme, host string) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
fmt.Printf("proxy: %v://%v%v\n", scheme, host, r.URL.Path) | |
r2 := r.Clone(r.Context()) | |
r2.URL.Scheme = scheme | |
r2.URL.Host = host | |
r2.RequestURI = "" | |
resp, err := client.Do(r2) | |
if err != nil { | |
fmt.Printf("bad gateway: %v\n", err) | |
w.WriteHeader(http.StatusBadGateway) | |
_, _ = fmt.Fprintf(w, `bad gateway: %v`, err) | |
return | |
} | |
header := w.Header() | |
for k, vs := range resp.Header { | |
for _, v := range vs { | |
header.Add(k, v) | |
} | |
} | |
w.WriteHeader(resp.StatusCode) | |
if _, err = io.Copy(w, resp.Body); err != nil { | |
fmt.Printf("gateway error: %v\n", err) | |
} | |
} | |
} | |
func main() { | |
h := http.NewServeMux() | |
h.Handle("/", proxy("http", "localhost:8081")) | |
h.Handle("/api/", proxy("http", "localhost:8080")) | |
h.Handle("/doc/", proxy("http", "localhost:8080")) | |
s := http.Server{ | |
Addr: ":8000", | |
Handler: h, | |
} | |
fmt.Printf("proxy is listening on :8000\n") | |
err := s.ListenAndServe() | |
fmt.Printf("%v\n", err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment