Skip to content

Commit ea86c3a

Browse files
chore: add teapot middleware (#16)
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.
1 parent ad5cf9c commit ea86c3a

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

cmd/server/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ func main() {
7070
r.HandleFunc("/method/trace", method.HandleTrace).Methods(http.MethodTrace)
7171

7272
handler := middleware.Fault(r)
73+
handler = middleware.Teapot(handler)
7374

7475
bind := ":8080"
7576
if bindArg != nil {

internal/middleware/teapot.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package middleware
2+
3+
import "net/http"
4+
5+
func Teapot(h http.Handler) http.Handler {
6+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
7+
format := r.Header.Get("x-teapot")
8+
if format == "" {
9+
h.ServeHTTP(w, r)
10+
return
11+
}
12+
13+
if format == "json" {
14+
w.Header().Set("Content-Type", "application/json")
15+
w.WriteHeader(http.StatusTeapot)
16+
w.Write([]byte(`{"message": "I'm a teapot"}`))
17+
return
18+
} else {
19+
w.Header().Set("Content-Type", "text/plain")
20+
w.WriteHeader(http.StatusTeapot)
21+
w.Write([]byte("I'm a teapot\n"))
22+
return
23+
}
24+
})
25+
}

0 commit comments

Comments
 (0)