1package webhook23import (4 "encoding"5 "errors"6 "strings"7)89// ContentType is the type of content that will be sent in a webhook request.10type ContentType int81112const (13 // ContentTypeJSON is the JSON content type.14 ContentTypeJSON ContentType = iota15 // ContentTypeForm is the form content type.16 ContentTypeForm17)1819var contentTypeStrings = map[ContentType]string{20 ContentTypeJSON: "application/json",21 ContentTypeForm: "application/x-www-form-urlencoded",22}2324// String returns the string representation of the content type.25func (c ContentType) String() string {26 return contentTypeStrings[c]27}2829var stringContentType = map[string]ContentType{30 "application/json": ContentTypeJSON,31 "application/x-www-form-urlencoded": ContentTypeForm,32}3334// ErrInvalidContentType is returned when the content type is invalid.35var ErrInvalidContentType = errors.New("invalid content type")3637// 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, nil42 }43 }4445 return -1, ErrInvalidContentType46}4748var (49 _ encoding.TextMarshaler = ContentType(0)50 _ encoding.TextUnmarshaler = (*ContentType)(nil)51)5253// UnmarshalText implements encoding.TextUnmarshaler.54func (c *ContentType) UnmarshalText(text []byte) error {55 ct, err := ParseContentType(string(text))56 if err != nil {57 return err58 }5960 *c = ct61 return nil62}6364// MarshalText implements encoding.TextMarshaler.65func (c ContentType) MarshalText() (text []byte, err error) {66 ct := c.String()67 if ct == "" {68 return nil, ErrInvalidContentType69 }7071 return []byte(ct), nil72}