forked from hairyhenderson/caddy-teapot-module
/
teapot.go
65 lines (53 loc) · 1.52 KB
/
teapot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Package teapot implements a sample Caddy v2 module. Its only purpose is to
// respond with "418 I'm a teapot" to every request.
//
// The simplest use could be in a Caddyfile like:
//
// localhost
//
// route {
// teapot
// }
package teapot
import (
"net/http"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func init() {
caddy.RegisterModule(Teapot{})
httpcaddyfile.RegisterHandlerDirective("teapot", parseCaddyfile)
}
// CaddyModule returns the Caddy module information.
func (Teapot) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.teapot",
New: func() caddy.Module { return new(Teapot) },
}
}
// Teapot implements a static "418 I'm a teapot" response to all requests on the route
type Teapot struct{}
// UnmarshalCaddyfile - this is a no-op
func (s *Teapot) UnmarshalCaddyfile(_ *caddyfile.Dispenser) error {
return nil
}
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
t := new(Teapot)
err := t.UnmarshalCaddyfile(h.Dispenser)
if err != nil {
return nil, err
}
return t, nil
}
func (s Teapot) ServeHTTP(w http.ResponseWriter, _ *http.Request, _ caddyhttp.Handler) error {
w.WriteHeader(http.StatusTeapot)
_, err := w.Write([]byte("I'm a teapot\r\n"))
return err
}
// Interface guards
var (
_ caddyhttp.MiddlewareHandler = (*Teapot)(nil)
_ caddyfile.Unmarshaler = (*Teapot)(nil)
)