overflow_service/server/gwrpc.go

90 lines
2.3 KiB
Go
Raw Normal View History

2017-06-22 03:07:45 +00:00
package server
import (
"flag"
2017-06-27 00:08:47 +00:00
pb "git.loafle.net/overflow/overflow_api_service/grpc"
2017-06-27 10:53:05 +00:00
ws "git.loafle.net/overflow/overflow_api_service/ws"
2017-06-27 00:08:47 +00:00
"github.com/golang/glog"
2017-06-22 03:07:45 +00:00
"github.com/grpc-ecosystem/grpc-gateway/runtime"
2017-06-27 00:08:47 +00:00
"golang.org/x/net/context"
2017-06-22 03:07:45 +00:00
"google.golang.org/grpc"
"net/http"
"strings"
2017-06-27 10:53:05 +00:00
"github.com/tmc/grpc-websocket-proxy/wsproxy"
"log"
"net"
2017-06-22 03:07:45 +00:00
)
var (
overflowEndpoint = flag.String("echo_endpoint", ":9090", "/v1/overflow/services")
2017-06-27 10:53:05 +00:00
grpcAddr = flag.String("grpcaddr", ":8001", "listen grpc addr")
httpAddr = flag.String("addr", ":8000", "listen http addr")
2017-06-22 03:07:45 +00:00
)
func RunGwRpc() (err error) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
2017-06-27 10:53:05 +00:00
if err := listenGRPC(*grpcAddr); err != nil {
return err
}
2017-06-22 03:07:45 +00:00
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
err = pb.RegisterOverflowGatewayHandlerFromEndpoint(ctx, mux, *overflowEndpoint, opts)
2017-06-27 10:53:05 +00:00
if err != nil {
return err
}
err = ws.RegisterWebSocketServiceHandlerFromEndpoint(ctx, mux, *grpcAddr, opts)
if err != nil {
return err
}
http.ListenAndServe(*httpAddr, wsproxy.WebsocketProxy(mux))
2017-06-22 03:07:45 +00:00
2017-06-27 10:53:05 +00:00
return http.ListenAndServe(":8080", wsproxy.WebsocketProxy(allowCORS(mux)))
}
func listenGRPC(listenAddr string) error {
lis, err := net.Listen("tcp", listenAddr)
2017-06-22 03:07:45 +00:00
if err != nil {
return err
}
2017-06-27 10:53:05 +00:00
grpcServer := grpc.NewServer()
ws.RegisterWebSocketServiceServer(grpcServer, &Server{})
go func() {
if err := grpcServer.Serve(lis); err != nil {
log.Println("serveGRPC err:", err)
}
}()
return nil
2017-06-22 03:07:45 +00:00
}
//https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/main.go
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"}
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, ","))
glog.Infof("preflight request for %s", r.URL.Path)
return
2017-06-27 00:08:47 +00:00
}