this repo has no description

:sparkles: middleware to validate query param and create request id

Changed files
+42 -2
+2
go.mod
··· 1 module github.com/Tulkdan/go-sse 2 3 go 1.24.2
··· 1 module github.com/Tulkdan/go-sse 2 3 go 1.24.2 4 + 5 + require github.com/google/uuid v1.6.0
+2
go.sum
···
··· 1 + github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 2 + github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+6 -2
main.go
··· 1 package main 2 3 import ( 4 "log" 5 "net/http" 6 ) ··· 9 pubsub := NewPubSub() 10 11 r := &http.ServeMux{} 12 - r.HandleFunc("GET /subscribe", pubsub.HandleSubscribe) 13 - r.HandleFunc("POST /publish", pubsub.HandlePublish) 14 15 server := http.Server{Addr: ":8000", Handler: r} 16 if err := server.ListenAndServe(); err != nil { 17 log.Fatal(err) 18 } 19 }
··· 1 package main 2 3 import ( 4 + "fmt" 5 "log" 6 "net/http" 7 ) ··· 10 pubsub := NewPubSub() 11 12 r := &http.ServeMux{} 13 + r.HandleFunc("GET /subscribe", middlewareRequestId(middlewareTopicQueryParam(pubsub.HandleSubscribe))) 14 + r.HandleFunc("POST /publish", middlewareRequestId(middlewareTopicQueryParam(pubsub.HandlePublish))) 15 16 server := http.Server{Addr: ":8000", Handler: r} 17 + fmt.Println("Starting server on 0.0.0.0:8000") 18 if err := server.ListenAndServe(); err != nil { 19 log.Fatal(err) 20 + } else { 21 + fmt.Println("Killing server") 22 } 23 }
+32
middleware.go
···
··· 1 + package main 2 + 3 + import ( 4 + "context" 5 + "errors" 6 + "net/http" 7 + 8 + "github.com/google/uuid" 9 + ) 10 + 11 + func middlewareTopicQueryParam(next http.HandlerFunc) http.HandlerFunc { 12 + return func(w http.ResponseWriter, r *http.Request) { 13 + topicName := r.URL.Query().Get("topic") 14 + if topicName == "" { 15 + http.Error(w, errors.New("Missing 'topic' query param").Error(), http.StatusBadRequest) 16 + return 17 + } 18 + 19 + next.ServeHTTP(w, r) 20 + } 21 + } 22 + 23 + func middlewareRequestId(next http.HandlerFunc) http.HandlerFunc { 24 + return func(w http.ResponseWriter, r *http.Request) { 25 + id, _ := uuid.NewV7() 26 + 27 + ctx := context.WithValue(r.Context(), "REQUEST_ID", id.String()) 28 + r = r.WithContext(ctx) 29 + 30 + next.ServeHTTP(w, r) 31 + } 32 + }