Skip to content

Commit a93e520

Browse files
committed
refactor(server.go): improve code lisibility
factorize repetitive blocks verify http method on openapi request
1 parent d4eef32 commit a93e520

File tree

1 file changed

+25
-14
lines changed

1 file changed

+25
-14
lines changed

internal/servers/server.go

+25-14
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net"
99
"net/http"
1010
"net/http/pprof"
11+
"os"
1112
"time"
1213

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

311-
if err = grpcV1.RegisterPermissionHandler(ctx, grpcMux, conn); err != nil {
312-
return err
313-
}
314-
if err = grpcV1.RegisterSchemaHandler(ctx, grpcMux, conn); err != nil {
315-
return err
312+
handlers := []func(context.Context, *runtime.ServeMux, *grpc.ClientConn) error{
313+
grpcV1.RegisterPermissionHandler,
314+
grpcV1.RegisterSchemaHandler,
315+
grpcV1.RegisterDataHandler,
316+
grpcV1.RegisterBundleHandler,
317+
grpcV1.RegisterTenancyHandler,
316318
}
317-
if err = grpcV1.RegisterDataHandler(ctx, grpcMux, conn); err != nil {
318-
return err
319-
}
320-
if err = grpcV1.RegisterBundleHandler(ctx, grpcMux, conn); err != nil {
321-
return err
322-
}
323-
if err = grpcV1.RegisterTenancyHandler(ctx, grpcMux, conn); err != nil {
324-
return err
319+
320+
for _, handler := range handlers {
321+
if err = handler(ctx, grpcMux, conn); err != nil {
322+
return fmt.Errorf("failed to register handler: %w", err)
323+
}
325324
}
326325

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

330330
if srv.HTTP.ExposeOpenAPI {
331331
httpMux.HandleFunc("/openapi.json", func(w http.ResponseWriter, r *http.Request) {
332-
http.ServeFile(w, r, "./docs/api-reference/openapi.json")
332+
if r.Method != http.MethodGet {
333+
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
334+
return
335+
}
336+
w.Header().Set("Content-Type", "application/json")
337+
w.Header().Set("Cache-Control", "public, max-age=3600")
338+
if _, err := os.Stat(openAPIPath); os.IsNotExist(err) {
339+
http.Error(w, "OpenAPI specification not found", http.StatusNotFound)
340+
return
341+
}
342+
343+
http.ServeFile(w, r, openAPIPath)
333344
})
334345
}
335346

0 commit comments

Comments
 (0)