restapi.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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(
  26. runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
  27. Marshaler: &runtime.JSONPb{
  28. MarshalOptions: protojson.MarshalOptions{
  29. UseProtoNames: true,
  30. EmitUnpopulated: true,
  31. },
  32. },
  33. }),
  34. )
  35. opts := []grpc.DialOption{grpc.WithInsecure()}
  36. err := gw.RegisterOliveTinApiHandlerFromEndpoint(ctx, mux, cfg.ListenAddressGrpcActions, opts)
  37. if err != nil {
  38. log.Errorf("Could not register REST API Handler %v", err)
  39. return err
  40. }
  41. return http.ListenAndServe(cfg.ListenAddressRestActions, cors.AllowCors(mux))
  42. }