-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdemo.go
77 lines (64 loc) · 1.66 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
67
68
69
70
71
72
73
74
75
76
77
// Package plugindemo a demo plugin.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"text/template"
"github.com/http-wasm/http-wasm-guest-tinygo/handler"
"github.com/http-wasm/http-wasm-guest-tinygo/handler/api"
)
func main() {
var config Config
err := json.Unmarshal(handler.Host.GetConfig(), &config)
if err != nil {
handler.Host.Log(api.LogLevelError, fmt.Sprintf("Could not load config %v", err))
os.Exit(1)
}
mw, err := New(config)
if err != nil {
handler.Host.Log(api.LogLevelError, fmt.Sprintf("Could not load config %v", err))
os.Exit(1)
}
handler.HandleRequestFn = mw.handleRequest
}
// Config the plugin configuration.
type Config struct {
Headers map[string]string `json:"headers,omitempty"`
}
// Demo a Demo plugin.
type Demo struct {
headers map[string]string
template *template.Template
}
// New created a new Demo plugin.
func New(config Config) (*Demo, error) {
if len(config.Headers) == 0 {
return nil, fmt.Errorf("headers cannot be empty")
}
return &Demo{
headers: config.Headers,
template: template.New("demo").Delims("[[", "]]"),
}, nil
}
func (a *Demo) handleRequest(req api.Request, resp api.Response) (next bool, reqCtx uint32) {
for key, value := range a.headers {
tmpl, err := a.template.Parse(value)
if err != nil {
resp.SetStatusCode(http.StatusInternalServerError)
resp.Body().Write([]byte(err.Error()))
return false, 0
}
writer := &bytes.Buffer{}
err = tmpl.Execute(writer, req)
if err != nil {
resp.SetStatusCode(http.StatusInternalServerError)
resp.Body().Write([]byte(err.Error()))
return false, 0
}
req.Headers().Set(key, writer.String())
}
return true, 0
}