forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
header.go
71 lines (59 loc) · 1.16 KB
/
header.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
66
67
68
69
70
71
package header
import (
"net/http"
"strings"
"github.com/micro/cli"
"github.com/micro/micro/plugin"
)
type header struct {
hd map[string]string
}
func (h *header) Flags() []cli.Flag {
return []cli.Flag{
cli.StringSliceFlag{
Name: "header",
Usage: "Headers to be set in the http response",
EnvVar: "HEADER",
},
}
}
func (h *header) Commands() []cli.Command {
return nil
}
func (h *header) Handler() plugin.Handler {
return func(ha http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for k, v := range h.hd {
// set header
r.Header.Set(k, v)
}
// exec handler
ha.ServeHTTP(w, r)
})
}
}
func (h *header) Init(ctx *cli.Context) error {
header := ctx.StringSlice("header")
// no op
if len(header) == 0 {
return nil
}
// iterate the string slice
for _, pair := range header {
parts := strings.Split(pair, "=")
if len(parts) < 2 {
continue
}
// set key-vals
h.hd[parts[0]] = strings.Join(parts[1:], "=")
}
return nil
}
func (h *header) String() string {
return "header"
}
func NewPlugin() plugin.Plugin {
return &header{
hd: make(map[string]string),
}
}