Skip to content

Instantly share code, notes, and snippets.

@messyidea
Last active June 7, 2016 04:48
Show Gist options
  • Select an option

  • Save messyidea/4c01dafb0facfa2c4d81522f3cb524db to your computer and use it in GitHub Desktop.

Select an option

Save messyidea/4c01dafb0facfa2c4d81522f3cb524db to your computer and use it in GitHub Desktop.
A simple google reverse proxy in Golang
// grproxy project main.go
package main
import (
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
func main() {
target, _ := url.Parse("http://www.google.com")
r := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.Host = target.Host //这才是关键
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
if target.RawQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = target.RawQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = target.RawQuery + "&" + req.URL.RawQuery
}
},
}
http.Handle("/", r)
http.ListenAndServe(":80", nil)
}
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment