Skip to content

Commit

Permalink
refactor(server.go): improve code lisibility
Browse files Browse the repository at this point in the history
factorize repetitive blocks
verify http method on openapi request
  • Loading branch information
leofvo committed Oct 28, 2024
1 parent d4eef32 commit a93e520
Showing 1 changed file with 25 additions and 14 deletions.
39 changes: 25 additions & 14 deletions internal/servers/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net"
"net/http"
"net/http/pprof"
"os"
"time"

"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
Expand Down Expand Up @@ -308,28 +309,38 @@ func (s *Container) Run(
// Create the gRPC gateway mux
grpcMux := runtime.NewServeMux(muxOpts...)

if err = grpcV1.RegisterPermissionHandler(ctx, grpcMux, conn); err != nil {
return err
}
if err = grpcV1.RegisterSchemaHandler(ctx, grpcMux, conn); err != nil {
return err
handlers := []func(context.Context, *runtime.ServeMux, *grpc.ClientConn) error{
grpcV1.RegisterPermissionHandler,
grpcV1.RegisterSchemaHandler,
grpcV1.RegisterDataHandler,
grpcV1.RegisterBundleHandler,
grpcV1.RegisterTenancyHandler,
}
if err = grpcV1.RegisterDataHandler(ctx, grpcMux, conn); err != nil {
return err
}
if err = grpcV1.RegisterBundleHandler(ctx, grpcMux, conn); err != nil {
return err
}
if err = grpcV1.RegisterTenancyHandler(ctx, grpcMux, conn); err != nil {
return err

for _, handler := range handlers {
if err = handler(ctx, grpcMux, conn); err != nil {
return fmt.Errorf("failed to register handler: %w", err)
}
}

// Create a new http.ServeMux for serving your OpenAPI file and gRPC gateway
httpMux := http.NewServeMux()
const openAPIPath = "./docs/api-reference/openapi.json"

if srv.HTTP.ExposeOpenAPI {
httpMux.HandleFunc("/openapi.json", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./docs/api-reference/openapi.json")
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "public, max-age=3600")
if _, err := os.Stat(openAPIPath); os.IsNotExist(err) {
http.Error(w, "OpenAPI specification not found", http.StatusNotFound)
return
}

http.ServeFile(w, r, openAPIPath)
})
}

Expand Down

0 comments on commit a93e520

Please sign in to comment.