Skip to content

Instantly share code, notes, and snippets.

@amsokol
Last active September 16, 2018 05:25
Show Gist options
  • Save amsokol/00c3c83000a1e741f6abd130843fba0e to your computer and use it in GitHub Desktop.
Save amsokol/00c3c83000a1e741f6abd130843fba0e to your computer and use it in GitHub Desktop.
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