Last active
July 24, 2020 08:25
-
-
Save 74th/782d7827f394ac1fc68cccbfa4d05b50 to your computer and use it in GitHub Desktop.
gRPC Revese Proxy
This file contains hidden or 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
// https://github.com/golang/go/issues/29928#issuecomment-458743053 | |
package main | |
import ( | |
"crypto/tls" | |
"flag" | |
"log" | |
"net" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"os" | |
"golang.org/x/net/http2" | |
) | |
// argument parser | |
var ( | |
upstream string | |
httpsSocket string | |
httpsCert string | |
httpsKey string | |
) | |
func init() { | |
flag.StringVar(&upstream, "upstream", "http://localhost:8080", "upstream (http://<ip>:<port>)") | |
flag.StringVar(&httpsSocket, "socket", ":18080", "local socket") | |
// openssl genrsa 2048 > server.key | |
// openssl req -new -key server.key > server.csr | |
// common name must be server host (ex: localhost) | |
// openssl x509 -in server.csr -days 3650 -req -signkey server.key -sha256 > server.crt | |
flag.StringVar(&httpsCert, "cert", "server.crt", "ssl cert") | |
flag.StringVar(&httpsKey, "key", "server.key", "key") | |
flag.Parse() | |
} | |
// main function | |
func main() { | |
log.SetPrefix("[proxy] ") | |
log.SetOutput(os.Stdout) | |
if upstream == "" { | |
log.Fatal("ERROR: missing argument upstream ") | |
} | |
url, _ := url.Parse(upstream) | |
proxy := &Upstream{target: url, proxy: httputil.NewSingleHostReverseProxy(url)} | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", proxy.handle) | |
log.Fatal(http.ListenAndServeTLS(httpsSocket, httpsCert, httpsKey, mux)) | |
} | |
// Upstream ... | |
type Upstream struct { | |
target *url.URL | |
proxy *httputil.ReverseProxy | |
} | |
func (p *Upstream) handle(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("X-Forwarded-For", r.Host) | |
p.proxy.Transport = | |
&http2.Transport{ | |
AllowHTTP: true, | |
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { | |
ta, err := net.ResolveTCPAddr(network, addr) | |
if err != nil { | |
return nil, err | |
} | |
return net.DialTCP(network, nil, ta) | |
}, | |
} | |
p.proxy.ServeHTTP(w, r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment