restapi.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package restapi
  2. import (
  3. "context"
  4. "github.com/grpc-ecosystem/grpc-gateway/runtime"
  5. log "github.com/sirupsen/logrus"
  6. "google.golang.org/grpc"
  7. "net/http"
  8. gw "github.com/jamesread/OliveTin/gen/grpc"
  9. cors "github.com/jamesread/OliveTin/internal/cors"
  10. config "github.com/jamesread/OliveTin/internal/config"
  11. )
  12. var (
  13. cfg *config.Config
  14. )
  15. func Start(listenAddressRest string, listenAddressGrpc string, globalConfig *config.Config) error {
  16. cfg = globalConfig
  17. ctx := context.Background()
  18. ctx, cancel := context.WithCancel(ctx)
  19. defer cancel()
  20. // The JSONPb.EmitDefaults is necssary, so "empty" fields are returned in JSON.
  21. mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))
  22. opts := []grpc.DialOption{grpc.WithInsecure()}
  23. err := gw.RegisterOliveTinApiHandlerFromEndpoint(ctx, mux, listenAddressGrpc, opts)
  24. if err != nil {
  25. log.Fatalf("gw error %v", err)
  26. }
  27. return http.ListenAndServe(listenAddressRest, cors.AllowCors(mux))
  28. }