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 66 67 68 69 70 71
| package mymodule
import ( "errors" "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" "net/http" )
func init() { caddy.RegisterModule(&HelloWorld{}) httpcaddyfile.RegisterHandlerDirective("hello_world", parseCaddyfile) }
type HelloWorld struct { Text string `json:"text,omitempty"` }
func (h *HelloWorld) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { if !d.Args(&h.Text) { return d.ArgErr() } if d.NextArg() { return d.ArgErr() } } return nil } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { hw := new(HelloWorld) err := hw.UnmarshalCaddyfile(h.Dispenser) return hw, err } func (h *HelloWorld) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { err := next.ServeHTTP(w, r) if err != nil { return err } w.Write([]byte(h.Text)) return nil } func (h HelloWorld) Validate() error { if h.Text == "" { return errors.New("the text is must!!!") } return nil } func (h *HelloWorld) Provision(ctx caddy.Context) error { return nil }
func (h HelloWorld) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.hello_world", New: func() caddy.Module { return new(HelloWorld) }, } }
var ( _ caddy.Provisioner = (*HelloWorld)(nil) _ caddy.Validator = (*HelloWorld)(nil) _ caddyhttp.MiddlewareHandler = (*HelloWorld)(nil) _ caddyfile.Unmarshaler = (*HelloWorld)(nil) )
|