Skip to content

Instantly share code, notes, and snippets.

@groob
Created July 18, 2017 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groob/66cf93cf4c799bae52ddc86c4238ad1f to your computer and use it in GitHub Desktop.
Save groob/66cf93cf4c799bae52ddc86c4238ad1f to your computer and use it in GitHub Desktop.
proxy grpc traffic with http
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