Created
July 18, 2017 17:38
-
-
Save groob/66cf93cf4c799bae52ddc86c4238ad1f to your computer and use it in GitHub Desktop.
proxy grpc traffic with http
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 ( | |
"crypto/tls" | |
"errors" | |
"log" | |
"net" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"strings" | |
"golang.org/x/net/http2" | |
) | |
func main() { | |
p, err := proxyForGRPC("https://localhost:8081", &tls.Config{InsecureSkipVerify: true}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
hf := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") { | |
p.ServeHTTP(w, r) | |
return | |
} | |
w.Write([]byte("hey there")) | |
}) | |
log.Fatal(http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", hf)) | |
} | |
func proxyForGRPC(backendURL string, conf *tls.Config) (*httputil.ReverseProxy, error) { | |
u, err := url.Parse(backendURL) | |
if err != nil { | |
return nil, err | |
} | |
if u.Scheme != "https" { | |
return nil, errors.New("can only proxy to a TLS backend") | |
} | |
dialTLS := func(network, addr string, cfg *tls.Config) (net.Conn, error) { | |
return tls.Dial(network, addr, conf) | |
} | |
transport := &http2.Transport{DialTLS: dialTLS} | |
p := httputil.NewSingleHostReverseProxy(u) | |
p.Transport = transport | |
return p, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment