types.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. "net/http"
  11. "time"
  12. )
  13. // Timestamp stores a timestamp, as sent by the Discord API.
  14. type Timestamp string
  15. // Parse parses a timestamp string into a time.Time object.
  16. // The only time this can fail is if Discord changes their timestamp format.
  17. func (t Timestamp) Parse() (time.Time, error) {
  18. return time.Parse(time.RFC3339, string(t))
  19. }
  20. // RESTError stores error information about a request with a bad response code.
  21. // Message is not always present, there are cases where api calls can fail
  22. // without returning a json message.
  23. type RESTError struct {
  24. Request *http.Request
  25. Response *http.Response
  26. ResponseBody []byte
  27. Message *APIErrorMessage // Message may be nil.
  28. }
  29. func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError {
  30. restErr := &RESTError{
  31. Request: req,
  32. Response: resp,
  33. ResponseBody: body,
  34. }
  35. // Attempt to decode the error and assume no message was provided if it fails
  36. var msg *APIErrorMessage
  37. err := json.Unmarshal(body, &msg)
  38. if err == nil {
  39. restErr.Message = msg
  40. }
  41. return restErr
  42. }
  43. func (r RESTError) Error() string {
  44. return "HTTP " + r.Response.Status + ", " + string(r.ResponseBody)
  45. }