Last active
September 16, 2018 05:25
-
-
Save amsokol/00c3c83000a1e741f6abd130843fba0e to your computer and use it in GitHub Desktop.
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 rest | |
import ( | |
"context" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"time" | |
"github.com/grpc-ecosystem/grpc-gateway/runtime" | |
"google.golang.org/grpc" | |
"github.com/amsokol/go-grpc-http-rest-microservice-tutorial/pkg/api/v1" | |
) | |
// RunServer runs HTTP/REST gateway | |
func RunServer(ctx context.Context, grpcPort, httpPort string) error { | |
ctx, cancel := context.WithCancel(ctx) | |
defer cancel() | |
mux := runtime.NewServeMux() | |
opts := []grpc.DialOption{grpc.WithInsecure()} | |
if err := v1.RegisterToDoServiceHandlerFromEndpoint(ctx, mux, "localhost:"+grpcPort, opts); err != nil { | |
log.Fatalf("failed to start HTTP gateway: %v", err) | |
} | |
srv := &http.Server{ | |
Addr: ":" + httpPort, | |
Handler: mux, | |
} | |
// graceful shutdown | |
c := make(chan os.Signal, 1) | |
signal.Notify(c, os.Interrupt) | |
go func() { | |
for range c { | |
// sig is a ^C, handle it | |
} | |
_, cancel := context.WithTimeout(ctx, 5*time.Second) | |
defer cancel() | |
_ = srv.Shutdown(ctx) | |
}() | |
log.Println("starting HTTP/REST gateway...") | |
return srv.ListenAndServe() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment