restapi.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package httpservers
  2. import (
  3. "context"
  4. "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
  5. log "github.com/sirupsen/logrus"
  6. "google.golang.org/grpc"
  7. "google.golang.org/protobuf/encoding/protojson"
  8. "net/http"
  9. gw "github.com/jamesread/OliveTin/gen/grpc"
  10. cors "github.com/jamesread/OliveTin/internal/cors"
  11. config "github.com/jamesread/OliveTin/internal/config"
  12. )
  13. var (
  14. cfg *config.Config
  15. )
  16. func startRestAPIServer(globalConfig *config.Config) error {
  17. cfg = globalConfig
  18. log.WithFields(log.Fields{
  19. "address": cfg.ListenAddressGrpcActions,
  20. }).Info("Starting REST API")
  21. ctx := context.Background()
  22. ctx, cancel := context.WithCancel(ctx)
  23. defer cancel()
  24. // The JSONPb.EmitDefaults is necssary, so "empty" fields are returned in JSON.
  25. //mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))
  26. mux := runtime.NewServeMux(
  27. runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
  28. Marshaler: &runtime.JSONPb{
  29. MarshalOptions: protojson.MarshalOptions{
  30. UseProtoNames: true,
  31. EmitUnpopulated: true,
  32. },
  33. },
  34. }),
  35. )
  36. opts := []grpc.DialOption{grpc.WithInsecure()}
  37. err := gw.RegisterOliveTinApiHandlerFromEndpoint(ctx, mux, cfg.ListenAddressGrpcActions, opts)
  38. if err != nil {
  39. log.Fatalf("gw error %v", err)
  40. }
  41. return http.ListenAndServe(cfg.ListenAddressRestActions, cors.AllowCors(mux))
  42. }