Skip to content

Instantly share code, notes, and snippets.

@khorevaa
Forked from thezelus/server.go
Created March 26, 2022 19:34
Show Gist options
  • Save khorevaa/5cf00e732b9f4ba27c03dd6e7c8dfda2 to your computer and use it in GitHub Desktop.
Save khorevaa/5cf00e732b9f4ba27c03dd6e7c8dfda2 to your computer and use it in GitHub Desktop.
golang NewSingleHostReverseProxy + gorilla mux
package main
import (
"net/http"
"net/http/httputil"
"net/url"
"github.com/gorilla/mux"
)
//Target url: https://httpbin.org/headers
//Url through proxy: http://localhost:3002/forward/headers
func main() {
target := "https://httpbin.org"
remote, err := url.Parse(target)
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
r := mux.NewRouter()
r.HandleFunc("/forward/{rest:.*}", handler(proxy))
http.Handle("/", r)
http.ListenAndServe(":3002", r)
}
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = mux.Vars(r)["rest"]
p.ServeHTTP(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment