62 lines
1.7 KiB
Go
62 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/grpc-ecosystem/grpc-gateway/runtime"
|
|
"golang.org/x/net/context"
|
|
"google.golang.org/grpc"
|
|
gw "src.dualinventive.com/go/devsim"
|
|
)
|
|
|
|
func listenAndServeGRPCGateway(httpEndpoint, grpcEndpoint string) error {
|
|
ctx := context.Background()
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
|
|
mux := runtime.NewServeMux()
|
|
opts := []grpc.DialOption{grpc.WithInsecure()}
|
|
err := gw.RegisterRepositoryServiceHandlerFromEndpoint(ctx, mux, grpcEndpoint, opts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = gw.RegisterSimulatorServiceHandlerFromEndpoint(ctx, mux, grpcEndpoint, opts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
s := &http.Server{
|
|
Addr: httpEndpoint,
|
|
Handler: allowCORS(mux),
|
|
}
|
|
|
|
log.Println("Listening devsimd-gateway on", httpEndpoint, "proxy to", grpcEndpoint)
|
|
return s.ListenAndServe()
|
|
}
|
|
|
|
// allowCORS allows Cross Origin Resoruce Sharing from any origin.
|
|
// Don't do this without consideration in production systems.
|
|
func allowCORS(h http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if origin := r.Header.Get("Origin"); origin != "" {
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
|
|
preflightHandler(w, r)
|
|
return
|
|
}
|
|
}
|
|
h.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func preflightHandler(w http.ResponseWriter, r *http.Request) {
|
|
headers := []string{"Content-Type", "Accept", "X-User-Agent", "X-Grpc-Web"}
|
|
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
|
|
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
|
|
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
|
|
log.Printf("preflight request for %s", r.URL.Path)
|
|
}
|