fix: critical bugs from code review (data corruption, error contract, HTTP hardening) (#5)
Co-authored-by: hermes <hermes@noreply.localhost> Co-committed-by: hermes <hermes@noreply.localhost>
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
@ -54,6 +55,7 @@ func setupHTTP(cfg config.HTTP, srv xhttp.Server, log *slog.Logger) *http.Server
|
||||
router := mux.NewRouter()
|
||||
|
||||
router.Use(
|
||||
middlewareRecovery(log),
|
||||
middlewareCustomWriterInjector(),
|
||||
mux.CORSMethodMiddleware(router),
|
||||
middlewareLogger(log),
|
||||
@ -101,6 +103,29 @@ func setupHTTP(cfg config.HTTP, srv xhttp.Server, log *slog.Logger) *http.Server
|
||||
}
|
||||
}
|
||||
|
||||
func middlewareRecovery(log *slog.Logger) mux.MiddlewareFunc {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
rec := recover()
|
||||
if rec == nil {
|
||||
return
|
||||
}
|
||||
if rec == http.ErrAbortHandler {
|
||||
panic(rec)
|
||||
}
|
||||
xcontext.LogWithError(
|
||||
r.Context(), log, fmt.Errorf("%v", rec), "recovered from panic",
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
)
|
||||
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func middlewareCustomWriterInjector() mux.MiddlewareFunc {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@ -50,7 +50,7 @@ func setupOtelSDK(ctx context.Context, cfg config.Trace) (shutdown shutdownFunc,
|
||||
return err
|
||||
}
|
||||
|
||||
resource, err := makeServiceResource(ctx)
|
||||
resource, err := makeServiceResource(ctx, cfg.Environment)
|
||||
if err != nil {
|
||||
return shutdown, fmt.Errorf("making service resource: %w", err)
|
||||
}
|
||||
@ -102,7 +102,10 @@ type TraceProviderParams struct {
|
||||
Type config.TraceClientType
|
||||
}
|
||||
|
||||
func makeServiceResource(ctx context.Context) (*resource.Resource, error) {
|
||||
func makeServiceResource(ctx context.Context, environment string) (*resource.Resource, error) {
|
||||
if environment == "" {
|
||||
environment = "development"
|
||||
}
|
||||
r, err := resource.New(
|
||||
ctx,
|
||||
resource.WithDetectors(
|
||||
@ -113,7 +116,7 @@ func makeServiceResource(ctx context.Context) (*resource.Resource, error) {
|
||||
resource.WithHost(),
|
||||
resource.WithAttributes(
|
||||
semconv.ServiceName("bigstats:kuriweb"),
|
||||
semconv.DeploymentEnvironment("production"),
|
||||
semconv.DeploymentEnvironment(environment),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user