├── AUTHOR ├── _tests ├── error.json ├── delete_response.json ├── common_response.json ├── github_bndr.json └── github_torvalds.json ├── .travis.yml ├── CONTRIBUTORS ├── .gitignore ├── examples ├── example_basic_auth.go └── example_oauth.go ├── api.go ├── README.md ├── resource.go ├── resource_test.go └── LICENSE.md /AUTHOR: -------------------------------------------------------------------------------- 1 | Vadim Kravcenko 2014 -------------------------------------------------------------------------------- /_tests/error.json: -------------------------------------------------------------------------------- 1 | { 2 | "message": "some error occured", 3 | "code": "E1234" 4 | } 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.2 5 | - 1.3 6 | - tip 7 | install: 8 | - go get github.com/stretchr/testify/assert 9 | - go get golang.org/x/oauth2 10 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # Contributors: git log --format='%aN <%aE>' | sort -uf 2 | bndr 3 | Henry 4 | Stanislav Seletskiy 5 | Vadim Kravcenko 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | gopencils -------------------------------------------------------------------------------- /_tests/delete_response.json: -------------------------------------------------------------------------------- 1 | { 2 | "args": {}, 3 | "data": "", 4 | "files": {}, 5 | "form": {}, 6 | "headers": { 7 | "Accept": "*/*", 8 | "Connection": "close", 9 | "Host": "httpbin.org", 10 | "User-Agent": "curl/7.37.0", 11 | "X-Request-Id": "b29e2435-926f-4fb4-bd1d-ec1b179e1523" 12 | }, 13 | "json": null, 14 | "origin": "95.91.230.168", 15 | "url": "https://httpbin.org/delete" 16 | } 17 | -------------------------------------------------------------------------------- /_tests/common_response.json: -------------------------------------------------------------------------------- 1 | { 2 | "args": {}, 3 | "data": "{\"Key\":\"Value1\"}", 4 | "files": {}, 5 | "form": {}, 6 | "headers": { 7 | "Accept": "*/*", 8 | "Connection": "close", 9 | "Content-Length": "16", 10 | "Content-Type": "application/json", 11 | "Host": "httpbin.org", 12 | "User-Agent": "curl/7.37.0", 13 | "X-Request-Id": "6268bee8-2ea0-4144-802a-6166fe18d84f" 14 | }, 15 | "json": { 16 | "Key": "Value1" 17 | }, 18 | "origin": "95.91.230.168", 19 | "url": "https://httpbin.org/post" 20 | } 21 | -------------------------------------------------------------------------------- /_tests/github_bndr.json: -------------------------------------------------------------------------------- 1 | { 2 | "login": "bndr", 3 | "id": 1145456, 4 | "avatar_url": "https://avatars.githubusercontent.com/u/1145456?", 5 | "gravatar_id": "8d05db0b0b8b74d5a0f93d0b1db22909", 6 | "url": "https://api.github.com/users/bndr", 7 | "html_url": "https://github.com/bndr", 8 | "followers_url": "https://api.github.com/users/bndr/followers", 9 | "following_url": "https://api.github.com/users/bndr/following{/other_user}", 10 | "gists_url": "https://api.github.com/users/bndr/gists{/gist_id}", 11 | "starred_url": "https://api.github.com/users/bndr/starred{/owner}{/repo}", 12 | "subscriptions_url": "https://api.github.com/users/bndr/subscriptions", 13 | "organizations_url": "https://api.github.com/users/bndr/orgs", 14 | "repos_url": "https://api.github.com/users/bndr/repos", 15 | "events_url": "https://api.github.com/users/bndr/events{/privacy}", 16 | "received_events_url": "https://api.github.com/users/bndr/received_events", 17 | "type": "User", 18 | "site_admin": false, 19 | "name": "Vadim Kravcenko", 20 | "company": "", 21 | "blog": "http://vadimkravcenko.com", 22 | "location": "Germany", 23 | "email": "bndrzz@gmail.com", 24 | "hireable": false, 25 | "bio": null, 26 | "public_repos": 17, 27 | "public_gists": 2, 28 | "followers": 13, 29 | "following": 0, 30 | "created_at": "2011-10-22T19:21:17Z", 31 | "updated_at": "2014-07-20T10:24:25Z" 32 | } 33 | -------------------------------------------------------------------------------- /examples/example_basic_auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/bndr/gopencils" 5 | ) 6 | 7 | func main() { 8 | // Create Basic Auth 9 | auth := gopencils.BasicAuth{"username", "password"} 10 | // Create New Api with our auth 11 | api := gopencils.Api("http://your-api-url.com/api/", &auth) 12 | 13 | // Maybe some payload to send along with the request? 14 | payload := map[string]interface{}{"Key": "Value1"} 15 | resp := new(respStruct) 16 | // Perform a GET request 17 | // URL Requested: http://your-api-url.com/api/users 18 | api.Res("users", &respStruct{}).Get() 19 | 20 | // Get Single Item 21 | api.Res("users", &respStruct{}).Id(1).Get() 22 | 23 | // Perform a GET request with Querystring 24 | querystring := map[string]string{"page": "100", "per_page": "1000"} 25 | // URL Requested: http://your-api-url.com/api/users/123/items?page=100&per_page=1000 26 | api.Res("users").Id(123).Res("items", resp).Get(querystring) 27 | 28 | // Or perform a POST Request 29 | // URL Requested: http://your-api-url.com/api/items/123 with payload as json Data 30 | api.Res("items", resp).Id(123).Post(payload) 31 | 32 | // Users endpoint 33 | users := api.Res("users") 34 | 35 | for i := 0; i < 10; i++ { 36 | // Create a new pointer to response Struct 37 | user := new(respStruct) 38 | // Get user with id i into the newly created response struct 39 | users.Id(i, user).Get() 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /_tests/github_torvalds.json: -------------------------------------------------------------------------------- 1 | { 2 | "login": "torvalds", 3 | "id": 1024025, 4 | "avatar_url": "https://avatars.githubusercontent.com/u/1024025?", 5 | "gravatar_id": "fb47627bc8c0bcdb36321edfbf02e916", 6 | "url": "https://api.github.com/users/torvalds", 7 | "html_url": "https://github.com/torvalds", 8 | "followers_url": "https://api.github.com/users/torvalds/followers", 9 | "following_url": "https://api.github.com/users/torvalds/following{/other_user}", 10 | "gists_url": "https://api.github.com/users/torvalds/gists{/gist_id}", 11 | "starred_url": "https://api.github.com/users/torvalds/starred{/owner}{/repo}", 12 | "subscriptions_url": "https://api.github.com/users/torvalds/subscriptions", 13 | "organizations_url": "https://api.github.com/users/torvalds/orgs", 14 | "repos_url": "https://api.github.com/users/torvalds/repos", 15 | "events_url": "https://api.github.com/users/torvalds/events{/privacy}", 16 | "received_events_url": "https://api.github.com/users/torvalds/received_events", 17 | "type": "User", 18 | "site_admin": false, 19 | "name": "Linus Torvalds", 20 | "company": "Linux Foundation", 21 | "blog": null, 22 | "location": "Portland, OR", 23 | "email": null, 24 | "hireable": false, 25 | "bio": null, 26 | "public_repos": 2, 27 | "public_gists": 0, 28 | "followers": 17605, 29 | "following": 0, 30 | "created_at": "2011-09-03T15:26:22Z", 31 | "updated_at": "2014-07-20T10:27:30Z" 32 | } 33 | -------------------------------------------------------------------------------- /api.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Vadim Kravcenko 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | // License for the specific language governing permissions and limitations 13 | // under the License. 14 | 15 | package gopencils 16 | 17 | import ( 18 | "crypto/tls" 19 | "net/http" 20 | "net/http/cookiejar" 21 | "net/url" 22 | ) 23 | 24 | // Basic Auth 25 | type BasicAuth struct { 26 | Username string 27 | Password string 28 | } 29 | 30 | // Main Api Instance. 31 | // No Options yet supported. 32 | type ApiStruct struct { 33 | BaseUrl *url.URL 34 | BasicAuth *BasicAuth 35 | Client *http.Client 36 | Cookies *cookiejar.Jar 37 | PathSuffix string 38 | } 39 | 40 | // Create a new API Instance and returns a Resource 41 | // Accepts URL as parameter, and either a Basic Auth or a OAuth2 Client. 42 | func Api(baseUrl string, options ...interface{}) *Resource { 43 | u, err := url.Parse(baseUrl) 44 | if err != nil { 45 | // TODO: don't panic.. 46 | panic("Api() - url.Parse(baseUrl) Error:" + err.Error()) 47 | } 48 | 49 | apiInstance := &ApiStruct{BaseUrl: u, BasicAuth: nil} 50 | 51 | for _, o := range options { 52 | switch v := o.(type) { 53 | case *BasicAuth: 54 | apiInstance.BasicAuth = v 55 | case *http.Client: 56 | apiInstance.Client = v 57 | case string: 58 | apiInstance.PathSuffix = v 59 | } 60 | } 61 | 62 | if apiInstance.Client == nil { 63 | apiInstance.Cookies, _ = cookiejar.New(nil) 64 | 65 | // Skip verify by default? 66 | tr := &http.Transport{ 67 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, 68 | } 69 | 70 | client := &http.Client{ 71 | Transport: tr, 72 | Jar: apiInstance.Cookies, 73 | } 74 | apiInstance.Client = client 75 | } 76 | return &Resource{Url: "", Api: apiInstance} 77 | } 78 | -------------------------------------------------------------------------------- /examples/example_oauth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang.org/x/oauth2" 5 | "github.com/bndr/gopencils" 6 | "net/http" 7 | ) 8 | 9 | // Oauth example taken from https://godoc.org/code.google.com/p/goauth2/oauth 10 | // The authenticated client must be passed to gopencils for OAuth to work. 11 | 12 | type respStruct struct { 13 | Args map[string]string 14 | Headers map[string]string 15 | Origin string 16 | Url string 17 | Authorization string 18 | } 19 | 20 | // Specify your configuration. (typically as a global variable) 21 | var config = &oauth2.Config{ 22 | ClientId: "YOUR_CLIENT_ID", 23 | ClientSecret: "YOUR_CLIENT_SECRET", 24 | Scope: "https://www.googleapis.com/auth/buzz", 25 | AuthURL: "https://accounts.google.com/o/oauth2/auth", 26 | TokenURL: "https://accounts.google.com/o/oauth2/token", 27 | RedirectURL: "http://you.example.org/handler", 28 | } 29 | 30 | // A landing page redirects to the OAuth provider to get the auth code. 31 | func landing(w http.ResponseWriter, r *http.Request) { 32 | http.Redirect(w, r, config.AuthCodeURL("foo"), http.StatusFound) 33 | } 34 | 35 | // The user will be redirected back to this handler, that takes the 36 | // "code" query parameter and Exchanges it for an access token. 37 | func handler(w http.ResponseWriter, r *http.Request) { 38 | t := &oauth2.Transport{Config: config} 39 | t.Exchange(r.FormValue("code")) 40 | // The Transport now has a valid Token. Create an *http.Client 41 | // with which we can make authenticated API requests. 42 | c := t.Client() 43 | 44 | // Now you can pass the authenticated Client to gopencils, and 45 | // it will be used to make all the requests 46 | api := gopencils.Api("http://your-api-url.com/api/", c) 47 | 48 | // Create a pointer to our response struct, which will hold the response 49 | re := &respStruct{} 50 | // Maybe some payload to send along with the request? 51 | payload := map[string]interface{}{"Key1": "Value1"} 52 | 53 | // Perform a GET request 54 | // URL Requested: http://your-api-url.com/api/users 55 | api.Res("users", re).Get() 56 | 57 | // Perform a GET request with Querystring 58 | querystring := map[string]string{"page": "100"} 59 | // URL Requested: http://your-api-url.com/api/users/123/items?page=100 60 | api.Res("users").Id(123).Res("items", re).Get(querystring) 61 | 62 | // Or perform a POST Request 63 | // URL Requested: http://your-api-url.com/api/items/123 with payload as json Data 64 | api.Res("items", re).Id(123).Post(payload) 65 | } 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gopencils - Dynamically consume REST APIs 2 | [![GoDoc](https://godoc.org/github.com/bndr/gopencils?status.svg)](https://godoc.org/github.com/bndr/gopencils) 3 | [![Build Status](https://travis-ci.org/bndr/gopencils.svg?branch=master)](https://travis-ci.org/bndr/gopencils) 4 | 5 | ## Summary 6 | Gopencils is a REST Client written in go. Easily consume any REST API's. Supported Response formats: JSON 7 | 8 | ## Install 9 | 10 | go get github.com/bndr/gopencils 11 | 12 | ## Simple to use 13 | 14 | Gopencils was designed to help you easily make requests to REST APIs without much hassle. It supports both Basic-Auth as well as OAuth. 15 | 16 | Example Basic-Auth 17 | 18 | ```go 19 | 20 | type UserExample struct { 21 | Id string 22 | Name string 23 | Origin string 24 | Url string 25 | SomeJsonField string 26 | } 27 | // Create Basic Auth 28 | auth := gopencils.BasicAuth{"username", "password"} 29 | 30 | // Create New Api with our auth 31 | api := gopencils.Api("http://your-api-url.com/api/", &auth) 32 | 33 | // Create a pointer to our response struct 34 | resp := &UserExample{} 35 | 36 | // Perform a GET request 37 | // URL Requested: http://your-api-url.com/api/users/1 38 | api.Res("users", resp).Id(1).Get() 39 | 40 | // Get Single Item 41 | api.Res("users", resp).Id(1).Get() 42 | 43 | // Perform a GET request with Querystring 44 | querystring := map[string]string{"page": "100", "per_page": "1000"} 45 | 46 | // URL Requested: http://your-api-url.com/api/users/123/items?page=100&per_page=1000 47 | resource := api.Res("users").Id(123).Res("items", resp).Get(querystring) 48 | 49 | // Now resp contains the returned json object 50 | // resource.Raw contains raw http response, 51 | 52 | // You can supply Path suffix to the api which will be applied to every url 53 | // e.g /items/id.json 54 | api := gopencils.Api("http://your-api-url.com/api/", &auth, ".json") 55 | 56 | ``` 57 | 58 | Example Github Api 59 | 60 | ```go 61 | 62 | package main 63 | 64 | import ( 65 | "fmt" 66 | "github.com/bndr/gopencils" 67 | ) 68 | 69 | type respStruct struct { 70 | Login string 71 | Id int 72 | Name string 73 | } 74 | 75 | func main() { 76 | api := gopencils.Api("https://api.github.com") 77 | // Users Resource 78 | users := api.Res("users") 79 | 80 | usernames := []string{"bndr", "torvalds", "coleifer"} 81 | 82 | for _, username := range usernames { 83 | // Create a new pointer to response Struct 84 | r := new(respStruct) 85 | // Get user with id i into the newly created response struct 86 | _, err := users.Id(username, r).Get() 87 | if err != nil { 88 | fmt.Println(err) 89 | } else { 90 | fmt.Println(r) 91 | } 92 | } 93 | } 94 | ``` 95 | More examples in the examples folder. 96 | 97 | ## Why? 98 | I work a lot with REST APIs and I caught myself writing the same code over and over, so I decided to make a library that would help me (and others) to quickly consume them. 99 | 100 | ## Is it ready? 101 | 102 | It is still in beta. But I would be glad if you could test it on your pet projects. The API will be improved, but no breaking changes are planned. 103 | 104 | ## Contribute 105 | 106 | All Contributions are welcome. The todo list is on the bottom of this README. Feel free to send a pull request. 107 | 108 | ## License 109 | 110 | Apache License 2.0 111 | 112 | ## TODO 113 | 1. Add more Options (Flexibility) 114 | 2. Support XML Response 115 | 3. Better Error Handling 116 | -------------------------------------------------------------------------------- /resource.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Vadim Kravcenko 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | // License for the specific language governing permissions and limitations 13 | // under the License. 14 | 15 | // Gopencils is a Golang REST Client with which you can easily consume REST API's. Supported Response formats: JSON 16 | package gopencils 17 | 18 | import ( 19 | "bytes" 20 | "encoding/json" 21 | "errors" 22 | "io" 23 | "net/http" 24 | "net/url" 25 | "strconv" 26 | ) 27 | 28 | var ErrCantUseAsQuery = errors.New("can't use options[0] as Query") 29 | 30 | // Resource is basically an url relative to given API Baseurl. 31 | type Resource struct { 32 | Api *ApiStruct 33 | Url string 34 | id string 35 | QueryValues url.Values 36 | Payload io.Reader 37 | Headers http.Header 38 | Response interface{} 39 | Raw *http.Response 40 | } 41 | 42 | // Creates a new Resource. 43 | func (r *Resource) Res(options ...interface{}) *Resource { 44 | if len(options) > 0 { 45 | var url string 46 | if len(r.Url) > 0 { 47 | url = r.Url + "/" + options[0].(string) 48 | } else { 49 | url = options[0].(string) 50 | } 51 | 52 | header := r.Headers 53 | if header == nil { 54 | header = http.Header{} 55 | } 56 | newR := &Resource{Url: url, Api: r.Api, Headers: header} 57 | 58 | if len(options) > 1 { 59 | newR.Response = options[1] 60 | } 61 | 62 | return newR 63 | } 64 | return r 65 | } 66 | 67 | // Same as Res() Method, but returns a Resource with url resource/:id 68 | func (r *Resource) Id(options ...interface{}) *Resource { 69 | if len(options) > 0 { 70 | id := "" 71 | switch v := options[0].(type) { 72 | default: 73 | id = v.(string) 74 | case int: 75 | id = strconv.Itoa(v) 76 | case int64: 77 | id = strconv.FormatInt(v, 10) 78 | } 79 | url := r.Url + "/" + id 80 | header := r.Headers 81 | if header == nil { 82 | header = http.Header{} 83 | } 84 | newR := &Resource{id: id, Url: url, Api: r.Api, Headers: header, Response: &r.Response} 85 | 86 | if len(options) > 1 { 87 | newR.Response = options[1] 88 | } 89 | return newR 90 | } 91 | return r 92 | } 93 | 94 | // Sets QueryValues for current Resource 95 | func (r *Resource) SetQuery(querystring map[string]string) *Resource { 96 | r.QueryValues = make(url.Values) 97 | for k, v := range querystring { 98 | r.QueryValues.Set(k, v) 99 | } 100 | return r 101 | } 102 | 103 | // Performs a GET request on given Resource 104 | // Accepts map[string]string as parameter, will be used as querystring. 105 | func (r *Resource) Get(options ...interface{}) (*Resource, error) { 106 | if len(options) > 0 { 107 | if qry, ok := options[0].(map[string]string); ok { 108 | r.SetQuery(qry) 109 | } else { 110 | return nil, ErrCantUseAsQuery 111 | } 112 | 113 | } 114 | return r.do("GET") 115 | } 116 | 117 | // Performs a HEAD request on given Resource 118 | // Accepts map[string]string as parameter, will be used as querystring. 119 | func (r *Resource) Head(options ...interface{}) (*Resource, error) { 120 | if len(options) > 0 { 121 | if qry, ok := options[0].(map[string]string); ok { 122 | r.SetQuery(qry) 123 | } else { 124 | return nil, ErrCantUseAsQuery 125 | } 126 | } 127 | return r.do("HEAD") 128 | } 129 | 130 | // Performs a PUT request on given Resource. 131 | // Accepts interface{} as parameter, will be used as payload. 132 | func (r *Resource) Put(options ...interface{}) (*Resource, error) { 133 | if len(options) > 0 { 134 | r.Payload = r.SetPayload(options[0]) 135 | } 136 | return r.do("PUT") 137 | } 138 | 139 | // Performs a POST request on given Resource. 140 | // Accepts interface{} as parameter, will be used as payload. 141 | func (r *Resource) Post(options ...interface{}) (*Resource, error) { 142 | if len(options) > 0 { 143 | r.Payload = r.SetPayload(options[0]) 144 | } 145 | return r.do("POST") 146 | } 147 | 148 | // Performs a Delete request on given Resource. 149 | // Accepts map[string]string as parameter, will be used as querystring. 150 | func (r *Resource) Delete(options ...interface{}) (*Resource, error) { 151 | if len(options) > 0 { 152 | if qry, ok := options[0].(map[string]string); ok { 153 | r.SetQuery(qry) 154 | } else { 155 | return nil, ErrCantUseAsQuery 156 | } 157 | } 158 | return r.do("DELETE") 159 | } 160 | 161 | // Performs a Delete request on given Resource. 162 | // Accepts map[string]string as parameter, will be used as querystring. 163 | func (r *Resource) Options(options ...interface{}) (*Resource, error) { 164 | if len(options) > 0 { 165 | if qry, ok := options[0].(map[string]string); ok { 166 | r.SetQuery(qry) 167 | } else { 168 | return nil, ErrCantUseAsQuery 169 | } 170 | } 171 | return r.do("OPTIONS") 172 | } 173 | 174 | // Performs a PATCH request on given Resource. 175 | // Accepts interface{} as parameter, will be used as payload. 176 | func (r *Resource) Patch(options ...interface{}) (*Resource, error) { 177 | if len(options) > 0 { 178 | r.Payload = r.SetPayload(options[0]) 179 | } 180 | return r.do("PATCH") 181 | } 182 | 183 | // Main method, opens the connection, sets basic auth, applies headers, 184 | // parses response json. 185 | func (r *Resource) do(method string) (*Resource, error) { 186 | url := *r.Api.BaseUrl 187 | if len(url.Path) > 0 { 188 | url.Path += "/" + r.Url 189 | } else { 190 | url.Path = r.Url 191 | } 192 | if r.Api.PathSuffix != "" { 193 | url.Path += r.Api.PathSuffix 194 | } 195 | 196 | url.RawQuery = r.QueryValues.Encode() 197 | req, err := http.NewRequest(method, url.String(), r.Payload) 198 | if err != nil { 199 | return r, err 200 | } 201 | 202 | if r.Api.BasicAuth != nil { 203 | req.SetBasicAuth(r.Api.BasicAuth.Username, r.Api.BasicAuth.Password) 204 | } 205 | 206 | if r.Headers != nil { 207 | for k, _ := range r.Headers { 208 | req.Header.Set(k, r.Headers.Get(k)) 209 | } 210 | } 211 | 212 | resp, err := r.Api.Client.Do(req) 213 | if err != nil { 214 | return r, err 215 | } 216 | 217 | r.Raw = resp 218 | 219 | if resp.StatusCode >= 400 { 220 | return r, nil 221 | } 222 | 223 | for k, _ := range r.Raw.Header { 224 | r.SetHeader(k, r.Raw.Header.Get(k)); 225 | } 226 | 227 | defer resp.Body.Close() 228 | 229 | err = json.NewDecoder(resp.Body).Decode(r.Response) 230 | if err != nil { 231 | return r, err 232 | } 233 | 234 | return r, nil 235 | } 236 | 237 | // Sets Payload for current Resource 238 | func (r *Resource) SetPayload(args interface{}) io.Reader { 239 | var b []byte 240 | b, _ = json.Marshal(args) 241 | r.SetHeader("Content-Type", "application/json") 242 | return bytes.NewBuffer(b) 243 | } 244 | 245 | // Sets Headers 246 | func (r *Resource) SetHeader(key string, value string) { 247 | r.Headers.Add(key, value) 248 | } 249 | 250 | // Overwrites the client that will be used for requests. 251 | // For example if you want to use your own client with OAuth2 252 | func (r *Resource) SetClient(c *http.Client) { 253 | r.Api.Client = c 254 | } 255 | -------------------------------------------------------------------------------- /resource_test.go: -------------------------------------------------------------------------------- 1 | package gopencils 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | "net/http/httptest" 8 | "strings" 9 | "testing" 10 | 11 | "github.com/stretchr/testify/assert" 12 | ) 13 | 14 | var ( 15 | testMux *http.ServeMux 16 | testSrv *httptest.Server 17 | ) 18 | 19 | func init() { 20 | testMux = http.NewServeMux() 21 | testSrv = httptest.NewServer(testMux) 22 | } 23 | 24 | type respStruct struct { 25 | Login string 26 | Id int 27 | Name string 28 | Message string 29 | } 30 | type httpbinResponse struct { 31 | Args string 32 | Headers map[string]string 33 | Url string 34 | Json map[string]interface{} 35 | } 36 | 37 | func TestResouceUrl(t *testing.T) { 38 | api := Api("https://test-url.com") 39 | assert.Equal(t, api.Api.BaseUrl.String(), "https://test-url.com", 40 | "Parsed Url Should match") 41 | api.SetQuery(map[string]string{"key1": "value1", "key2": "value2"}) 42 | assert.Equal(t, api.QueryValues.Encode(), "key1=value1&key2=value2", 43 | "Parsed QueryString Url Should match") 44 | assert.Equal(t, api.Url, "", "Base Url Should be empty") 45 | } 46 | 47 | func TestCanUsePathInResourceUrl(t *testing.T) { 48 | testMux.HandleFunc("/path/to/api/resname/id123", 49 | func(rw http.ResponseWriter, req *http.Request) { 50 | fmt.Fprintln(rw, `{"Test":"Okay"}`) 51 | }) 52 | 53 | res := Api(testSrv.URL+"/path/to/api", nil) 54 | 55 | var resp struct { 56 | Test string 57 | } 58 | 59 | _, err := res.Res("resname").Id("id123", &resp).Get() 60 | assert.Nil(t, err, "err should be nil") 61 | assert.Equal(t, "Okay", resp.Test, "resp shoul be Okay") 62 | } 63 | 64 | func TestCanUseAuthForApi(t *testing.T) { 65 | api := Api("https://test-url.com", &BasicAuth{"username", "password"}) 66 | assert.Equal(t, api.Api.BasicAuth.Username, "username", 67 | "Username should match") 68 | assert.Equal(t, api.Api.BasicAuth.Password, "password", 69 | "Password should match") 70 | } 71 | 72 | func TestCanGetResource(t *testing.T) { 73 | // github stubs 74 | testMux.HandleFunc("/users/bndr", 75 | func(rw http.ResponseWriter, req *http.Request) { 76 | fmt.Fprintln(rw, readJson("_tests/github_bndr.json")) 77 | }) 78 | testMux.HandleFunc("/users/torvalds", 79 | func(rw http.ResponseWriter, req *http.Request) { 80 | fmt.Fprintln(rw, readJson("_tests/github_torvalds.json")) 81 | }) 82 | 83 | api := Api(testSrv.URL) 84 | // Users endpoint 85 | users := api.Res("users") 86 | 87 | usernames := []string{"bndr", "torvalds"} 88 | 89 | for _, username := range usernames { 90 | // Create a new pointer to response Struct 91 | r := new(respStruct) 92 | // Get user with id i into the newly created response struct 93 | _, err := users.Id(username, r).Get() 94 | if err != nil { 95 | t.Log("Error Getting Data from Test API\nErr:", err) 96 | } else { 97 | assert.Equal(t, r.Message, "", "Error message must be empty") 98 | assert.Equal(t, r.Login, username, "Username should be equal") 99 | } 100 | } 101 | resp := new(respStruct) 102 | api.Res("users", resp).Id("bndr").Get() 103 | assert.Equal(t, resp.Login, "bndr") 104 | resp2 := new(respStruct) 105 | api.Res("users").Id("bndr", resp2).Get() 106 | assert.Equal(t, resp2.Login, "bndr") 107 | } 108 | 109 | func TestCanCreateResource(t *testing.T) { 110 | testMux.HandleFunc("/post", 111 | func(rw http.ResponseWriter, req *http.Request) { 112 | assert.Equal(t, req.Method, "POST", "unexpected Method") 113 | assert.Equal(t, req.URL.Path, "/post", "unexpected Path") 114 | assert.Equal(t, req.Header.Get("Content-Type"), "application/json", 115 | "Expected json content type") 116 | fmt.Fprintln(rw, readJson("_tests/common_response.json")) 117 | }) 118 | 119 | api := Api(testSrv.URL) 120 | payload := map[string]interface{}{"Key": "Value1"} 121 | r := new(httpbinResponse) 122 | api.Res("post", r).Post(payload) 123 | assert.Equal(t, r.Json["Key"], "Value1", "Payload must match") 124 | } 125 | 126 | func TestCanPutResource(t *testing.T) { 127 | testMux.HandleFunc("/put", 128 | func(rw http.ResponseWriter, req *http.Request) { 129 | assert.Equal(t, req.Method, "PUT", "unexpected Method") 130 | assert.Equal(t, req.URL.Path, "/put", "unexpected Path") 131 | assert.Equal(t, req.Header.Get("Content-Type"), "application/json", 132 | "Expected json content type") 133 | fmt.Fprintln(rw, readJson("_tests/common_response.json")) 134 | }) 135 | 136 | api := Api(testSrv.URL) 137 | payload := map[string]interface{}{"Key": "Value1"} 138 | r := new(httpbinResponse) 139 | api.Res("put", r).Put(payload) 140 | assert.Equal(t, r.Json["Key"], "Value1", "Payload must match") 141 | } 142 | 143 | func TestCanDeleteResource(t *testing.T) { 144 | testMux.HandleFunc("/delete", 145 | func(rw http.ResponseWriter, req *http.Request) { 146 | assert.Equal(t, req.Method, "DELETE", "unexpected Method") 147 | assert.Equal(t, req.URL.Path, "/delete", "unexpected Path") 148 | fmt.Fprintln(rw, readJson("_tests/delete_response.json")) 149 | }) 150 | 151 | api := Api(testSrv.URL) 152 | r := new(httpbinResponse) 153 | api.Id("delete", r).Delete() 154 | assert.Equal(t, r.Url, "https://httpbin.org/delete", "Url must match") 155 | } 156 | 157 | func TestPathSuffix(t *testing.T) { 158 | testMux.HandleFunc("/item/32.json", 159 | func(rw http.ResponseWriter, req *http.Request) { 160 | assert.Equal(t, req.Method, "GET", "unexpected Method") 161 | assert.Equal(t, req.URL.Path, "/item/32.json", "unexpected Path") 162 | fmt.Fprintln(rw, readJson("_tests/common_response.json")) 163 | }) 164 | 165 | api := Api(testSrv.URL, ".json") 166 | r := new(httpbinResponse) 167 | api.Res("item", r).Id(32).Get() 168 | assert.Equal(t, r.Json["Key"], "Value1", "Payload must match") 169 | } 170 | 171 | func TestPathSuffixWithQueryParam(t *testing.T) { 172 | testMux.HandleFunc("/item/42.json", 173 | func(rw http.ResponseWriter, req *http.Request) { 174 | assert.Equal(t, req.Method, "GET", "unexpected Method") 175 | assert.Equal(t, req.URL.Path, "/item/42.json", "unexpected Path") 176 | assert.Equal(t, req.URL.Query().Get("param"), "test", "unexpected QueryParam") 177 | fmt.Fprintln(rw, readJson("_tests/common_response.json")) 178 | }) 179 | 180 | api := Api(testSrv.URL, ".json") 181 | r := new(httpbinResponse) 182 | api.Res("item", r).Id(42).Get(map[string]string{"param": "test"}) 183 | assert.Equal(t, r.Json["Key"], "Value1", "Payload must match") 184 | } 185 | 186 | func TestResourceId(t *testing.T) { 187 | api := Api("https://test-url.com") 188 | assert.Equal(t, api.Res("users").Id("test").Url, "users/test", 189 | "Url should match") 190 | assert.Equal(t, api.Res("users").Id(123).Res("items").Id(111).Url, 191 | "users/123/items/111", "Multilevel Url should match") 192 | assert.Equal(t, api.Res("users").Id(int64(9223372036854775807)).Url, "users/9223372036854775807", 193 | "int64 id should work") 194 | } 195 | 196 | func TestDoNotDecodeBodyOnErr(t *testing.T) { 197 | tests := []int{ 198 | 400, 401, 500, 501, 199 | } 200 | 201 | actualData := strings.TrimSpace(readJson("_tests/error.json")) 202 | 203 | // will be changed later 204 | code := 0 205 | testMux.HandleFunc("/error", 206 | func(rw http.ResponseWriter, req *http.Request) { 207 | rw.WriteHeader(code) 208 | fmt.Fprintln(rw, actualData) 209 | }) 210 | 211 | api := Api(testSrv.URL) 212 | 213 | for _, code = range tests { 214 | resp := make(map[string]interface{}) 215 | r, err := api.Id("error", &resp).Get() 216 | if err != nil { 217 | t.Fatal(err) 218 | } 219 | 220 | assert.Equal(t, map[string]interface{}{}, resp, 221 | fmt.Sprintf("response should be unparsed: %d", code)) 222 | 223 | respData, err := ioutil.ReadAll(r.Raw.Body) 224 | if err != nil { 225 | t.Fatal(err) 226 | } 227 | 228 | assert.Equal(t, actualData, strings.TrimSpace(string(respData)), 229 | fmt.Sprintf("response body is not accessible: %d", code)) 230 | } 231 | } 232 | 233 | func readJson(path string) string { 234 | buf, err := ioutil.ReadFile(path) 235 | if err != nil { 236 | panic(err) 237 | } 238 | 239 | return string(buf) 240 | } 241 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------