Skip to content

Commit

Permalink
chore: add teapot middleware (#16)
Browse files Browse the repository at this point in the history
This change adds a new HTTP middleware to that
intercepts requests with an `x-teapot` header and
responds with a 418 status code and a message in
json or text format depending on the value of the
header.

This middleware provides a simple mechanism to
trigger error responses.
  • Loading branch information
disintegrator authored Oct 4, 2024
1 parent ad5cf9c commit ea86c3a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ func main() {
r.HandleFunc("/method/trace", method.HandleTrace).Methods(http.MethodTrace)

handler := middleware.Fault(r)
handler = middleware.Teapot(handler)

bind := ":8080"
if bindArg != nil {
Expand Down
25 changes: 25 additions & 0 deletions internal/middleware/teapot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package middleware

import "net/http"

func Teapot(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
format := r.Header.Get("x-teapot")
if format == "" {
h.ServeHTTP(w, r)
return
}

if format == "json" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTeapot)
w.Write([]byte(`{"message": "I'm a teapot"}`))
return
} else {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusTeapot)
w.Write([]byte("I'm a teapot\n"))
return
}
})
}

0 comments on commit ea86c3a

Please sign in to comment.