-
Notifications
You must be signed in to change notification settings - Fork 20
/
visitorip.go
50 lines (41 loc) · 1004 Bytes
/
visitorip.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
package visitorip
import (
"fmt"
"io"
"net/http"
"os"
"github.com/RussellLuo/caddy-ext/dynamichandler/caddymiddleware"
)
// Middleware implements an HTTP handler that writes the
// visitor's IP address to a file or stream.
type Middleware struct {
// The file or stream to write to. Can be "stdout"
// or "stderr".
Output string `json:"output,omitempty"`
w io.Writer
}
func New() caddymiddleware.Middleware {
return &Middleware{}
}
func (m *Middleware) Provision() error {
switch m.Output {
case "stdout":
m.w = os.Stdout
case "stderr":
m.w = os.Stderr
default:
return fmt.Errorf("an output stream is required")
}
return nil
}
func (m *Middleware) Validate() error {
if m.w == nil {
return fmt.Errorf("no writer")
}
return nil
}
func (m *Middleware) Cleanup() error { return nil }
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddymiddleware.Handler) error {
_, _ = m.w.Write([]byte(r.RemoteAddr + "\n"))
return next.ServeHTTP(w, r)
}