feat: custom JSON marshal/unmarshal functions (#1162)

This commit is contained in:
Fedor Lapshin 2022-04-17 21:39:18 +03:00 committed by GitHub
parent 6f6516bf79
commit eda859edc9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 22 additions and 16 deletions

View file

@ -70,7 +70,7 @@ type ActionsRow struct {
func (r ActionsRow) MarshalJSON() ([]byte, error) { func (r ActionsRow) MarshalJSON() ([]byte, error) {
type actionsRow ActionsRow type actionsRow ActionsRow
return json.Marshal(struct { return Marshal(struct {
actionsRow actionsRow
Type ComponentType `json:"type"` Type ComponentType `json:"type"`
}{ }{
@ -145,7 +145,7 @@ func (b Button) MarshalJSON() ([]byte, error) {
b.Style = PrimaryButton b.Style = PrimaryButton
} }
return json.Marshal(struct { return Marshal(struct {
button button
Type ComponentType `json:"type"` Type ComponentType `json:"type"`
}{ }{
@ -192,7 +192,7 @@ func (SelectMenu) Type() ComponentType {
func (m SelectMenu) MarshalJSON() ([]byte, error) { func (m SelectMenu) MarshalJSON() ([]byte, error) {
type selectMenu SelectMenu type selectMenu SelectMenu
return json.Marshal(struct { return Marshal(struct {
selectMenu selectMenu
Type ComponentType `json:"type"` Type ComponentType `json:"type"`
}{ }{
@ -222,7 +222,7 @@ func (TextInput) Type() ComponentType {
func (m TextInput) MarshalJSON() ([]byte, error) { func (m TextInput) MarshalJSON() ([]byte, error) {
type inputText TextInput type inputText TextInput
return json.Marshal(struct { return Marshal(struct {
inputText inputText
Type ComponentType `json:"type"` Type ComponentType `json:"type"`
}{ }{

View file

@ -39,6 +39,13 @@ var (
ErrUnauthorized = errors.New("HTTP request was unauthorized. This could be because the provided token was not a bot token. Please add \"Bot \" to the start of your token. https://discord.com/developers/docs/reference#authentication-example-bot-token-authorization-header") ErrUnauthorized = errors.New("HTTP request was unauthorized. This could be because the provided token was not a bot token. Please add \"Bot \" to the start of your token. https://discord.com/developers/docs/reference#authentication-example-bot-token-authorization-header")
) )
var (
// Marshal defines function used to encode JSON payloads
Marshal func(v interface{}) ([]byte, error) = json.Marshal
// Unmarshal defines function used to decode JSON payloads
Unmarshal func(src []byte, v interface{}) error = json.Unmarshal
)
// RESTError stores error information about a request with a bad response code. // RESTError stores error information about a request with a bad response code.
// Message is not always present, there are cases where api calls can fail // Message is not always present, there are cases where api calls can fail
// without returning a json message. // without returning a json message.
@ -60,7 +67,7 @@ func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTErro
// Attempt to decode the error and assume no message was provided if it fails // Attempt to decode the error and assume no message was provided if it fails
var msg *APIErrorMessage var msg *APIErrorMessage
err := json.Unmarshal(body, &msg) err := Unmarshal(body, &msg)
if err == nil { if err == nil {
restErr.Message = msg restErr.Message = msg
} }
@ -94,7 +101,7 @@ func (s *Session) Request(method, urlStr string, data interface{}) (response []b
func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string) (response []byte, err error) { func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string) (response []byte, err error) {
var body []byte var body []byte
if data != nil { if data != nil {
body, err = json.Marshal(data) body, err = Marshal(data)
if err != nil { if err != nil {
return return
} }
@ -193,7 +200,7 @@ func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b
} }
case 429: // TOO MANY REQUESTS - Rate limiting case 429: // TOO MANY REQUESTS - Rate limiting
rl := TooManyRequests{} rl := TooManyRequests{}
err = json.Unmarshal(response, &rl) err = Unmarshal(response, &rl)
if err != nil { if err != nil {
s.log(LogError, "rate limit unmarshal error, %s", err) s.log(LogError, "rate limit unmarshal error, %s", err)
return return
@ -225,7 +232,7 @@ func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b
} }
func unmarshal(data []byte, v interface{}) error { func unmarshal(data []byte, v interface{}) error {
err := json.Unmarshal(data, v) err := Unmarshal(data, v)
if err != nil { if err != nil {
return fmt.Errorf("%w: %s", ErrJSONUnmarshal, err) return fmt.Errorf("%w: %s", ErrJSONUnmarshal, err)
} }
@ -2292,7 +2299,7 @@ func (s *Session) WebhookMessage(webhookID, token, messageID string) (message *M
return return
} }
err = json.Unmarshal(body, &message) err = Unmarshal(body, &message)
return return
} }

View file

@ -878,7 +878,7 @@ func (p GuildScheduledEventParams) MarshalJSON() ([]byte, error) {
type guildScheduledEventParams GuildScheduledEventParams type guildScheduledEventParams GuildScheduledEventParams
if p.EntityType == GuildScheduledEventEntityTypeExternal && p.ChannelID == "" { if p.EntityType == GuildScheduledEventEntityTypeExternal && p.ChannelID == "" {
return json.Marshal(struct { return Marshal(struct {
guildScheduledEventParams guildScheduledEventParams
ChannelID json.RawMessage `json:"channel_id"` ChannelID json.RawMessage `json:"channel_id"`
}{ }{
@ -887,7 +887,7 @@ func (p GuildScheduledEventParams) MarshalJSON() ([]byte, error) {
}) })
} }
return json.Marshal(guildScheduledEventParams(p)) return Marshal(guildScheduledEventParams(p))
} }
// GuildScheduledEventEntityMetadata holds additional metadata for guild scheduled event. // GuildScheduledEventEntityMetadata holds additional metadata for guild scheduled event.
@ -1129,7 +1129,7 @@ func (t *TimeStamps) UnmarshalJSON(b []byte) error {
End float64 `json:"end,omitempty"` End float64 `json:"end,omitempty"`
Start float64 `json:"start,omitempty"` Start float64 `json:"start,omitempty"`
}{} }{}
err := json.Unmarshal(b, &temp) err := Unmarshal(b, &temp)
if err != nil { if err != nil {
return err return err
} }
@ -1267,7 +1267,7 @@ func (t *TooManyRequests) UnmarshalJSON(b []byte) error {
Message string `json:"message"` Message string `json:"message"`
RetryAfter float64 `json:"retry_after"` RetryAfter float64 `json:"retry_after"`
}{} }{}
err := json.Unmarshal(b, &u) err := Unmarshal(b, &u)
if err != nil { if err != nil {
return err return err
} }
@ -1687,7 +1687,7 @@ func (activity *Activity) UnmarshalJSON(b []byte) error {
Instance bool `json:"instance,omitempty"` Instance bool `json:"instance,omitempty"`
Flags int `json:"flags,omitempty"` Flags int `json:"flags,omitempty"`
}{} }{}
err := json.Unmarshal(b, &temp) err := Unmarshal(b, &temp)
if err != nil { if err != nil {
return err return err
} }

View file

@ -2,7 +2,6 @@ package discordgo
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"mime/multipart" "mime/multipart"
@ -30,7 +29,7 @@ func MultipartBodyWithJSON(data interface{}, files []*File) (requestContentType
body := &bytes.Buffer{} body := &bytes.Buffer{}
bodywriter := multipart.NewWriter(body) bodywriter := multipart.NewWriter(body)
payload, err := json.Marshal(data) payload, err := Marshal(data)
if err != nil { if err != nil {
return return
} }