forked from masci/flickr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
93 lines (79 loc) · 2.09 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package flickr
import (
"encoding/xml"
"io/ioutil"
"net/http"
flickErr "gopkg.in/masci/flickr.v2/error"
)
// Interface for Flickr request objects
type FlickrResponse interface {
HasErrors() bool
ErrorCode() int
ErrorMsg() string
SetErrorStatus(bool)
SetErrorCode(int)
SetErrorMsg(string)
}
// Base type representing responses from Flickr API
type BasicResponse struct {
XMLName xml.Name `xml:"rsp"`
// Status might contain "fail" or "ok" strings
Status string `xml:"stat,attr"`
// Flickr API error detail
Error struct {
Code int `xml:"code,attr"`
Message string `xml:"msg,attr"`
} `xml:"err"`
Extra string `xml:",innerxml"`
}
// Return whether a response contains errors
func (r *BasicResponse) HasErrors() bool {
return r.Status != "ok"
}
// Return the error code (0 if no errors)
func (r *BasicResponse) ErrorCode() int {
return r.Error.Code
}
// Return error message string (empty string if no errors)
func (r *BasicResponse) ErrorMsg() string {
return r.Error.Message
}
// Set error status explicitly
func (r *BasicResponse) SetErrorStatus(hasErrors bool) {
if hasErrors {
r.Status = "fail"
} else {
r.Status = "ok"
}
}
// Set error code explicitly
func (r *BasicResponse) SetErrorCode(code int) {
r.Error.Code = code
}
// Set error message explicitly
func (r *BasicResponse) SetErrorMsg(msg string) {
r.Error.Message = msg
}
// Given an http.Response retrieved from Flickr, unmarshal results
// into a FlickrResponse struct.
func parseApiResponse(res *http.Response, r FlickrResponse) error {
defer res.Body.Close()
responseBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
err = xml.Unmarshal(responseBody, r)
if err != nil {
// In case of OAuth errors (signature, parameters, etc) Flicker does not
// return a REST response but raw text (!), so the unmarshalling could fail.
// We need to artificially build a FlickrResponse and manually fill in
// the error string.
r.SetErrorStatus(true)
r.SetErrorCode(-1)
r.SetErrorMsg(string(responseBody))
}
if r.HasErrors() {
return flickErr.NewError(flickErr.ApiError, r.ErrorMsg())
}
return nil
}