...

Source file src/github.com/tmc/grpc-websocket-proxy/_examples/cmd/wsechoserver/main.go

Documentation: github.com/tmc/grpc-websocket-proxy/_examples/cmd/wsechoserver

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"log"
     7  	"net"
     8  	"net/http"
     9  	_ "net/http/pprof"
    10  
    11  	_ "golang.org/x/net/trace"
    12  
    13  	"github.com/golang/glog"
    14  	"github.com/grpc-ecosystem/grpc-gateway/runtime"
    15  	"github.com/tmc/grpc-websocket-proxy/examples/cmd/wsechoserver/echoserver"
    16  	"github.com/tmc/grpc-websocket-proxy/wsproxy"
    17  	"golang.org/x/net/context"
    18  	"google.golang.org/grpc"
    19  )
    20  
    21  var (
    22  	grpcAddr  = flag.String("grpcaddr", ":8001", "listen grpc addr")
    23  	httpAddr  = flag.String("addr", ":8000", "listen http addr")
    24  	debugAddr = flag.String("debugaddr", ":8002", "listen debug addr")
    25  )
    26  
    27  func run() error {
    28  	ctx := context.Background()
    29  	ctx, cancel := context.WithCancel(ctx)
    30  	defer cancel()
    31  
    32  	if err := listenGRPC(*grpcAddr); err != nil {
    33  		return err
    34  	}
    35  
    36  	mux := runtime.NewServeMux()
    37  	opts := []grpc.DialOption{grpc.WithInsecure()}
    38  	err := echoserver.RegisterEchoServiceHandlerFromEndpoint(ctx, mux, *grpcAddr, opts)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	go http.ListenAndServe(*debugAddr, nil)
    43  	fmt.Println("listening")
    44  	http.ListenAndServe(*httpAddr, wsproxy.WebsocketProxy(mux))
    45  	return nil
    46  }
    47  
    48  func listenGRPC(listenAddr string) error {
    49  	lis, err := net.Listen("tcp", listenAddr)
    50  	if err != nil {
    51  		return err
    52  	}
    53  	grpcServer := grpc.NewServer()
    54  	echoserver.RegisterEchoServiceServer(grpcServer, &Server{})
    55  	go func() {
    56  		if err := grpcServer.Serve(lis); err != nil {
    57  			log.Println("serveGRPC err:", err)
    58  		}
    59  	}()
    60  	return nil
    61  
    62  }
    63  
    64  func main() {
    65  	flag.Parse()
    66  	defer glog.Flush()
    67  
    68  	if err := run(); err != nil {
    69  		glog.Fatal(err)
    70  	}
    71  }
    72  

View as plain text