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 (
49	_ encoding.TextMarshaler   = ContentType(0)
50	_ encoding.TextUnmarshaler = (*ContentType)(nil)
51)
52
53// UnmarshalText implements encoding.TextUnmarshaler.
54func (c *ContentType) UnmarshalText(text []byte) error {
55	ct, err := ParseContentType(string(text))
56	if err != nil {
57		return err
58	}
59
60	*c = ct
61	return nil
62}
63
64// MarshalText implements encoding.TextMarshaler.
65func (c ContentType) MarshalText() (text []byte, err error) {
66	ct := c.String()
67	if ct == "" {
68		return nil, ErrInvalidContentType
69	}
70
71	return []byte(ct), nil
72}