types.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains custom types, currently only a timestamp wrapper.
  7. package discordgo
  8. import (
  9. "encoding/json"
  10. "fmt"
  11. "net/http"
  12. "time"
  13. )
  14. // Timestamp stores a timestamp, as sent by the Discord API.
  15. type Timestamp string
  16. // Parse parses a timestamp string into a time.Time object.
  17. // The only time this can fail is if Discord changes their timestamp format.
  18. func (t Timestamp) Parse() (time.Time, error) {
  19. return time.Parse(time.RFC3339, string(t))
  20. }
  21. // RESTError stores error information about a request with a bad response code.
  22. // Message is not always present, there are cases where api calls can fail
  23. // without returning a json message.
  24. type RESTError struct {
  25. Request *http.Request
  26. Response *http.Response
  27. ResponseBody []byte
  28. Message *APIErrorMessage // Message may be nil.
  29. }
  30. func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError {
  31. restErr := &RESTError{
  32. Request: req,
  33. Response: resp,
  34. ResponseBody: body,
  35. }
  36. // Attempt to decode the error and assume no message was provided if it fails
  37. var msg *APIErrorMessage
  38. err := json.Unmarshal(body, &msg)
  39. if err == nil {
  40. restErr.Message = msg
  41. }
  42. return restErr
  43. }
  44. func (r RESTError) Error() string {
  45. return fmt.Sprintf("HTTP %s, %s", r.Response.Status, r.ResponseBody)
  46. }