github.com/onflow/flow-go@v0.33.17/engine/access/rpc/http_server.go (about)

     1  package rpc
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/improbable-eng/grpc-web/go/grpcweb"
     7  	"google.golang.org/grpc"
     8  )
     9  
    10  type HTTPHeader struct {
    11  	Key   string
    12  	Value string
    13  }
    14  
    15  var defaultHTTPHeaders = []HTTPHeader{
    16  	{
    17  		Key:   "Access-Control-Allow-Origin",
    18  		Value: "*",
    19  	},
    20  	{
    21  		Key:   "Access-Control-Allow-Methods",
    22  		Value: "POST, GET, OPTIONS, PUT, DELETE",
    23  	},
    24  	{
    25  		Key:   "Access-Control-Allow-Headers",
    26  		Value: "*",
    27  	},
    28  }
    29  
    30  // newHTTPProxyServer creates a new HTTP GRPC proxy server.
    31  func newHTTPProxyServer(grpcServer *grpc.Server) *http.Server {
    32  	wrappedServer := grpcweb.WrapServer(
    33  		grpcServer,
    34  		grpcweb.WithOriginFunc(func(origin string) bool { return true }),
    35  	)
    36  
    37  	// register gRPC HTTP proxy
    38  	mux := http.NewServeMux()
    39  	mux.Handle("/", wrappedHandler(wrappedServer, defaultHTTPHeaders))
    40  
    41  	httpServer := &http.Server{
    42  		Handler: mux,
    43  	}
    44  
    45  	return httpServer
    46  }
    47  
    48  func wrappedHandler(wrappedServer *grpcweb.WrappedGrpcServer, headers []HTTPHeader) http.HandlerFunc {
    49  	return func(res http.ResponseWriter, req *http.Request) {
    50  		setResponseHeaders(res, headers)
    51  
    52  		if req.Method == "OPTIONS" {
    53  			return
    54  		}
    55  
    56  		wrappedServer.ServeHTTP(res, req)
    57  	}
    58  }
    59  
    60  func setResponseHeaders(w http.ResponseWriter, headers []HTTPHeader) {
    61  	for _, header := range headers {
    62  		w.Header().Set(header.Key, header.Value)
    63  	}
    64  }