-
Notifications
You must be signed in to change notification settings - Fork 45
/
demo.go
66 lines (55 loc) · 1.33 KB
/
demo.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
// Package plugindemo a demo plugin.
package plugindemo
import (
"bytes"
"context"
"fmt"
"net/http"
"text/template"
)
// Config the plugin configuration.
type Config struct {
Headers map[string]string `json:"headers,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{
Headers: make(map[string]string),
}
}
// Demo a Demo plugin.
type Demo struct {
next http.Handler
headers map[string]string
name string
template *template.Template
}
// New created a new Demo plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.Headers) == 0 {
return nil, fmt.Errorf("headers cannot be empty")
}
return &Demo{
headers: config.Headers,
next: next,
name: name,
template: template.New("demo").Delims("[[", "]]"),
}, nil
}
func (a *Demo) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
for key, value := range a.headers {
tmpl, err := a.template.Parse(value)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
writer := &bytes.Buffer{}
err = tmpl.Execute(writer, req)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
req.Header.Set(key, writer.String())
}
a.next.ServeHTTP(rw, req)
}