-
Notifications
You must be signed in to change notification settings - Fork 345
/
inlinecontent.go
87 lines (73 loc) · 1.73 KB
/
inlinecontent.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
78
79
80
81
82
83
84
85
86
87
package builtin
import (
"bytes"
"io/ioutil"
"net/http"
"strconv"
"github.com/zalando/skipper/filters"
)
type inlineContent struct {
text string
mime string
}
// Creates a filter spec for the inlineContent() filter.
//
// Usage of the filter:
//
// * -> status(420) -> inlineContent("Enhance Your Calm") -> <shunt>
//
// Or:
//
// * -> inlineContent("{\"foo\": 42}", "application/json") -> <shunt>
//
// It accepts two arguments: the content and the optional content type.
// When the content type is not set, it tries to detect it using
// http.DetectContentType.
//
// The filter shunts the request with status code 200.
//
func NewInlineContent() filters.Spec {
return &inlineContent{}
}
func (c *inlineContent) Name() string { return InlineContentName }
func stringArg(a interface{}) (s string, err error) {
var ok bool
s, ok = a.(string)
if !ok {
err = filters.ErrInvalidFilterParameters
}
return
}
func (c *inlineContent) CreateFilter(args []interface{}) (filters.Filter, error) {
if len(args) == 0 || len(args) > 2 {
return nil, filters.ErrInvalidFilterParameters
}
var (
f inlineContent
err error
)
f.text, err = stringArg(args[0])
if err != nil {
return nil, err
}
if len(args) == 2 {
f.mime, err = stringArg(args[1])
if err != nil {
return nil, err
}
} else {
f.mime = http.DetectContentType([]byte(f.text))
}
return &f, nil
}
func (c *inlineContent) Request(ctx filters.FilterContext) {
ctx.Serve(&http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Content-Type": []string{c.mime},
"Content-Length": []string{strconv.Itoa(len(c.text))},
},
Body: ioutil.NopCloser(bytes.NewBufferString(c.text)),
})
}
func (c *inlineContent) Response(filters.FilterContext) {}