Created
March 29, 2020 03:43
-
-
Save chengjianhua/e747a5680583181414a244ff8606c2a7 to your computer and use it in GitHub Desktop.
grpc gateway golang example #grpc #grpc-gateway #golang
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 ( | |
"context" // Use "golang.org/x/net/context" for Golang version <= 1.6 | |
"flag" | |
"net/http" | |
"github.com/golang/glog" | |
"github.com/grpc-ecosystem/grpc-gateway/runtime" | |
"google.golang.org/grpc" | |
gw "appos/protobuf/protobuf/mistral/v1beta1" | |
) | |
var ( | |
// command-line options: | |
// gRPC server endpoint | |
grpcServerEndpoint = flag.String("grpc-server-endpoint", "localhost:8082", "gRPC server endpoint") | |
grpcGatewayListen = flag.String("listen", ":9999", "grpc gateway 服务的监听端口") | |
) | |
func run() error { | |
ctx := context.Background() | |
ctx, cancel := context.WithCancel(ctx) | |
defer cancel() | |
// Register gRPC server endpoint | |
// Note: Make sure the gRPC server is running properly and accessible | |
mux := runtime.NewServeMux() | |
opts := []grpc.DialOption{grpc.WithInsecure()} | |
err := gw.RegisterComponentSVCHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts) | |
if err != nil { | |
return err | |
} | |
// Start HTTP server (and proxy calls to gRPC server endpoint) | |
return http.ListenAndServe(*grpcGatewayListen, mux) | |
} | |
func main() { | |
flag.Parse() | |
defer glog.Flush() | |
if err := run(); err != nil { | |
glog.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment