1package webhook
2
3import (
4 "encoding"
5 "errors"
6 "strings"
7)
8
9// ContentType is the type of content that will be sent in a webhook request.
10type ContentType int8
11
12const (
13 // ContentTypeJSON is the JSON content type.
14 ContentTypeJSON ContentType = iota
15 // ContentTypeForm is the form content type.
16 ContentTypeForm
17)
18
19var contentTypeStrings = map[ContentType]string{
20 ContentTypeJSON: "application/json",
21 ContentTypeForm: "application/x-www-form-urlencoded",
22}
23
24// String returns the string representation of the content type.
25func (c ContentType) String() string {
26 return contentTypeStrings[c]
27}
28
29var stringContentType = map[string]ContentType{
30 "application/json": ContentTypeJSON,
31 "application/x-www-form-urlencoded": ContentTypeForm,
32}
33
34// ErrInvalidContentType is returned when the content type is invalid.
35var ErrInvalidContentType = errors.New("invalid content type")
36
37// ParseContentType parses a content type string and returns the content type.
38func ParseContentType(s string) (ContentType, error) {
39 for k, v := range stringContentType {
40 if strings.HasPrefix(s, k) {
41 return v, nil
42 }
43 }
44
45 return -1, ErrInvalidContentType
46}
47
48var _ encoding.TextMarshaler = ContentType(0)
49var _ encoding.TextUnmarshaler = (*ContentType)(nil)
50
51// UnmarshalText implements encoding.TextUnmarshaler.
52func (c *ContentType) UnmarshalText(text []byte) error {
53 ct, err := ParseContentType(string(text))
54 if err != nil {
55 return err
56 }
57
58 *c = ct
59 return nil
60}
61
62// MarshalText implements encoding.TextMarshaler.
63func (c ContentType) MarshalText() (text []byte, err error) {
64 ct := c.String()
65 if ct == "" {
66 return nil, ErrInvalidContentType
67 }
68
69 return []byte(ct), nil
70}