github.com/koko1123/flow-go-1@v0.29.6/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  // NewHTTPServer creates and intializes a new HTTP GRPC proxy server
    31  func NewHTTPServer(
    32  	grpcServer *grpc.Server,
    33  	address string,
    34  ) *http.Server {
    35  	wrappedServer := grpcweb.WrapServer(
    36  		grpcServer,
    37  		grpcweb.WithOriginFunc(func(origin string) bool { return true }),
    38  	)
    39  
    40  	mux := http.NewServeMux()
    41  
    42  	// register gRPC HTTP proxy
    43  	mux.Handle("/", wrappedHandler(wrappedServer, defaultHTTPHeaders))
    44  
    45  	httpServer := &http.Server{
    46  		Addr:    address,
    47  		Handler: mux,
    48  	}
    49  
    50  	return httpServer
    51  }
    52  
    53  func wrappedHandler(wrappedServer *grpcweb.WrappedGrpcServer, headers []HTTPHeader) http.HandlerFunc {
    54  	return func(res http.ResponseWriter, req *http.Request) {
    55  		setResponseHeaders(res, headers)
    56  
    57  		if req.Method == "OPTIONS" {
    58  			return
    59  		}
    60  
    61  		wrappedServer.ServeHTTP(res, req)
    62  	}
    63  }
    64  
    65  func setResponseHeaders(w http.ResponseWriter, headers []HTTPHeader) {
    66  	for _, header := range headers {
    67  		w.Header().Set(header.Key, header.Value)
    68  	}
    69  }