[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n*.prof\n\ngopencils"
  },
  {
    "path": ".travis.yml",
    "content": "language: go\n\ngo:\n  - 1.2\n  - 1.3\n  - tip\ninstall:\n  - go get github.com/stretchr/testify/assert\n  - go get golang.org/x/oauth2\n"
  },
  {
    "path": "AUTHOR",
    "content": "Vadim Kravcenko 2014"
  },
  {
    "path": "CONTRIBUTORS",
    "content": "# Contributors: git log --format='%aN <%aE>' | sort -uf\nbndr <bndrzz@gmail.com>\nHenry <cryptix@riseup.net>\nStanislav Seletskiy <s.seletskiy@gmail.com>\nVadim Kravcenko <bndrzz@gmail.com>\n"
  },
  {
    "path": "LICENSE.md",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "# Gopencils - Dynamically consume REST APIs\n[![GoDoc](https://godoc.org/github.com/bndr/gopencils?status.svg)](https://godoc.org/github.com/bndr/gopencils)\n[![Build Status](https://travis-ci.org/bndr/gopencils.svg?branch=master)](https://travis-ci.org/bndr/gopencils)\n\n## Summary\nGopencils is a REST Client written in go. Easily consume any REST API's. Supported Response formats: JSON\n\n## Install\n\n    go get github.com/bndr/gopencils\n\n## Simple to use\n\nGopencils was designed to help you easily make requests to REST APIs without much hassle. It supports both Basic-Auth as well as OAuth.\n\nExample Basic-Auth\n\n```go\n\ntype UserExample struct {\n\tId            string\n\tName          string\n\tOrigin        string\n\tUrl           string\n\tSomeJsonField string\n}\n// Create Basic Auth\nauth := gopencils.BasicAuth{\"username\", \"password\"}\n\n// Create New Api with our auth\napi := gopencils.Api(\"http://your-api-url.com/api/\", &auth)\n\n// Create a pointer to our response struct\nresp := &UserExample{}\n\n// Perform a GET request\n// URL Requested: http://your-api-url.com/api/users/1\napi.Res(\"users\", resp).Id(1).Get()\n\n// Get Single Item\napi.Res(\"users\", resp).Id(1).Get()\n\n// Perform a GET request with Querystring\nquerystring := map[string]string{\"page\": \"100\", \"per_page\": \"1000\"}\n\n// URL Requested: http://your-api-url.com/api/users/123/items?page=100&per_page=1000\nresource := api.Res(\"users\").Id(123).Res(\"items\", resp).Get(querystring)\n\n// Now resp contains the returned json object\n// resource.Raw contains raw http response,\n\n// You can supply Path suffix to the api which will be applied to every url\n// e.g /items/id.json\napi := gopencils.Api(\"http://your-api-url.com/api/\", &auth, \".json\")\n\n```\n\nExample Github Api\n\n```go\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com/bndr/gopencils\"\n)\n\ntype respStruct struct {\n\tLogin string\n\tId    int\n\tName  string\n}\n\nfunc main() {\n\tapi := gopencils.Api(\"https://api.github.com\")\n\t// Users Resource\n\tusers := api.Res(\"users\")\n\n\tusernames := []string{\"bndr\", \"torvalds\", \"coleifer\"}\n\n\tfor _, username := range usernames {\n\t\t// Create a new pointer to response Struct\n\t\tr := new(respStruct)\n\t\t// Get user with id i into the newly created response struct\n\t\t_, err := users.Id(username, r).Get()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\tfmt.Println(r)\n\t\t}\n\t}\n}\n```\nMore examples in the examples folder.\n\n## Why?\nI 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.\n\n## Is it ready?\n\nIt 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.\n\n## Contribute\n\nAll Contributions are welcome. The todo list is on the bottom of this README. Feel free to send a pull request.\n\n## License\n\nApache License 2.0\n\n## TODO\n1. Add more Options (Flexibility)\n2. Support XML Response\n3. Better Error Handling\n"
  },
  {
    "path": "_tests/common_response.json",
    "content": "{\n  \"args\": {},\n  \"data\": \"{\\\"Key\\\":\\\"Value1\\\"}\",\n  \"files\": {},\n  \"form\": {},\n  \"headers\": {\n    \"Accept\": \"*/*\",\n    \"Connection\": \"close\",\n    \"Content-Length\": \"16\",\n    \"Content-Type\": \"application/json\",\n    \"Host\": \"httpbin.org\",\n    \"User-Agent\": \"curl/7.37.0\",\n    \"X-Request-Id\": \"6268bee8-2ea0-4144-802a-6166fe18d84f\"\n  },\n  \"json\": {\n    \"Key\": \"Value1\"\n  },\n  \"origin\": \"95.91.230.168\",\n  \"url\": \"https://httpbin.org/post\"\n}\n"
  },
  {
    "path": "_tests/delete_response.json",
    "content": "{\n  \"args\": {},\n  \"data\": \"\",\n  \"files\": {},\n  \"form\": {},\n  \"headers\": {\n    \"Accept\": \"*/*\",\n    \"Connection\": \"close\",\n    \"Host\": \"httpbin.org\",\n    \"User-Agent\": \"curl/7.37.0\",\n    \"X-Request-Id\": \"b29e2435-926f-4fb4-bd1d-ec1b179e1523\"\n  },\n  \"json\": null,\n  \"origin\": \"95.91.230.168\",\n  \"url\": \"https://httpbin.org/delete\"\n}\n"
  },
  {
    "path": "_tests/error.json",
    "content": "{\n  \"message\": \"some error occured\",\n  \"code\": \"E1234\"\n}\n"
  },
  {
    "path": "_tests/github_bndr.json",
    "content": "{\n  \"login\": \"bndr\",\n  \"id\": 1145456,\n  \"avatar_url\": \"https://avatars.githubusercontent.com/u/1145456?\",\n  \"gravatar_id\": \"8d05db0b0b8b74d5a0f93d0b1db22909\",\n  \"url\": \"https://api.github.com/users/bndr\",\n  \"html_url\": \"https://github.com/bndr\",\n  \"followers_url\": \"https://api.github.com/users/bndr/followers\",\n  \"following_url\": \"https://api.github.com/users/bndr/following{/other_user}\",\n  \"gists_url\": \"https://api.github.com/users/bndr/gists{/gist_id}\",\n  \"starred_url\": \"https://api.github.com/users/bndr/starred{/owner}{/repo}\",\n  \"subscriptions_url\": \"https://api.github.com/users/bndr/subscriptions\",\n  \"organizations_url\": \"https://api.github.com/users/bndr/orgs\",\n  \"repos_url\": \"https://api.github.com/users/bndr/repos\",\n  \"events_url\": \"https://api.github.com/users/bndr/events{/privacy}\",\n  \"received_events_url\": \"https://api.github.com/users/bndr/received_events\",\n  \"type\": \"User\",\n  \"site_admin\": false,\n  \"name\": \"Vadim Kravcenko\",\n  \"company\": \"\",\n  \"blog\": \"http://vadimkravcenko.com\",\n  \"location\": \"Germany\",\n  \"email\": \"bndrzz@gmail.com\",\n  \"hireable\": false,\n  \"bio\": null,\n  \"public_repos\": 17,\n  \"public_gists\": 2,\n  \"followers\": 13,\n  \"following\": 0,\n  \"created_at\": \"2011-10-22T19:21:17Z\",\n  \"updated_at\": \"2014-07-20T10:24:25Z\"\n}\n"
  },
  {
    "path": "_tests/github_torvalds.json",
    "content": "{\n  \"login\": \"torvalds\",\n  \"id\": 1024025,\n  \"avatar_url\": \"https://avatars.githubusercontent.com/u/1024025?\",\n  \"gravatar_id\": \"fb47627bc8c0bcdb36321edfbf02e916\",\n  \"url\": \"https://api.github.com/users/torvalds\",\n  \"html_url\": \"https://github.com/torvalds\",\n  \"followers_url\": \"https://api.github.com/users/torvalds/followers\",\n  \"following_url\": \"https://api.github.com/users/torvalds/following{/other_user}\",\n  \"gists_url\": \"https://api.github.com/users/torvalds/gists{/gist_id}\",\n  \"starred_url\": \"https://api.github.com/users/torvalds/starred{/owner}{/repo}\",\n  \"subscriptions_url\": \"https://api.github.com/users/torvalds/subscriptions\",\n  \"organizations_url\": \"https://api.github.com/users/torvalds/orgs\",\n  \"repos_url\": \"https://api.github.com/users/torvalds/repos\",\n  \"events_url\": \"https://api.github.com/users/torvalds/events{/privacy}\",\n  \"received_events_url\": \"https://api.github.com/users/torvalds/received_events\",\n  \"type\": \"User\",\n  \"site_admin\": false,\n  \"name\": \"Linus Torvalds\",\n  \"company\": \"Linux Foundation\",\n  \"blog\": null,\n  \"location\": \"Portland, OR\",\n  \"email\": null,\n  \"hireable\": false,\n  \"bio\": null,\n  \"public_repos\": 2,\n  \"public_gists\": 0,\n  \"followers\": 17605,\n  \"following\": 0,\n  \"created_at\": \"2011-09-03T15:26:22Z\",\n  \"updated_at\": \"2014-07-20T10:27:30Z\"\n}\n"
  },
  {
    "path": "api.go",
    "content": "// Copyright 2014 Vadim Kravcenko\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"): you may\n// not use this file except in compliance with the License. You may obtain\n// a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n// License for the specific language governing permissions and limitations\n// under the License.\n\npackage gopencils\n\nimport (\n\t\"crypto/tls\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n)\n\n// Basic Auth\ntype BasicAuth struct {\n\tUsername string\n\tPassword string\n}\n\n// Main Api Instance.\n// No Options yet supported.\ntype ApiStruct struct {\n\tBaseUrl    *url.URL\n\tBasicAuth  *BasicAuth\n\tClient     *http.Client\n\tCookies    *cookiejar.Jar\n\tPathSuffix string\n}\n\n// Create a new API Instance and returns a Resource\n// Accepts URL as parameter, and either a Basic Auth or a OAuth2 Client.\nfunc Api(baseUrl string, options ...interface{}) *Resource {\n\tu, err := url.Parse(baseUrl)\n\tif err != nil {\n\t\t// TODO: don't panic..\n\t\tpanic(\"Api() - url.Parse(baseUrl) Error:\" + err.Error())\n\t}\n\n\tapiInstance := &ApiStruct{BaseUrl: u, BasicAuth: nil}\n\n\tfor _, o := range options {\n\t\tswitch v := o.(type) {\n\t\tcase *BasicAuth:\n\t\t\tapiInstance.BasicAuth = v\n\t\tcase *http.Client:\n\t\t\tapiInstance.Client = v\n\t\tcase string:\n\t\t\tapiInstance.PathSuffix = v\n\t\t}\n\t}\n\n\tif apiInstance.Client == nil {\n\t\tapiInstance.Cookies, _ = cookiejar.New(nil)\n\n\t\t// Skip verify by default?\n\t\ttr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\n\t\tclient := &http.Client{\n\t\t\tTransport: tr,\n\t\t\tJar:       apiInstance.Cookies,\n\t\t}\n\t\tapiInstance.Client = client\n\t}\n\treturn &Resource{Url: \"\", Api: apiInstance}\n}\n"
  },
  {
    "path": "examples/example_basic_auth.go",
    "content": "package main\n\nimport (\n\t\"github.com/bndr/gopencils\"\n)\n\nfunc main() {\n\t// Create Basic Auth\n\tauth := gopencils.BasicAuth{\"username\", \"password\"}\n\t// Create New Api with our auth\n\tapi := gopencils.Api(\"http://your-api-url.com/api/\", &auth)\n\n\t// Maybe some payload to send along with the request?\n\tpayload := map[string]interface{}{\"Key\": \"Value1\"}\n\tresp := new(respStruct)\n\t// Perform a GET request\n\t// URL Requested: http://your-api-url.com/api/users\n\tapi.Res(\"users\", &respStruct{}).Get()\n\n\t// Get Single Item\n\tapi.Res(\"users\", &respStruct{}).Id(1).Get()\n\n\t// Perform a GET request with Querystring\n\tquerystring := map[string]string{\"page\": \"100\", \"per_page\": \"1000\"}\n\t// URL Requested: http://your-api-url.com/api/users/123/items?page=100&per_page=1000\n\tapi.Res(\"users\").Id(123).Res(\"items\", resp).Get(querystring)\n\n\t// Or perform a POST Request\n\t// URL Requested: http://your-api-url.com/api/items/123 with payload as json Data\n\tapi.Res(\"items\", resp).Id(123).Post(payload)\n\n\t// Users endpoint\n\tusers := api.Res(\"users\")\n\n\tfor i := 0; i < 10; i++ {\n\t\t// Create a new pointer to response Struct\n\t\tuser := new(respStruct)\n\t\t// Get user with id i into the newly created response struct\n\t\tusers.Id(i, user).Get()\n\t}\n\n}\n"
  },
  {
    "path": "examples/example_oauth.go",
    "content": "package main\n\nimport (\n\t\"golang.org/x/oauth2\"\n\t\"github.com/bndr/gopencils\"\n\t\"net/http\"\n)\n\n// Oauth example taken from https://godoc.org/code.google.com/p/goauth2/oauth\n// The authenticated client must be passed to gopencils for OAuth to work.\n\ntype respStruct struct {\n\tArgs          map[string]string\n\tHeaders       map[string]string\n\tOrigin        string\n\tUrl           string\n\tAuthorization string\n}\n\n// Specify your configuration. (typically as a global variable)\nvar config = &oauth2.Config{\n\tClientId:     \"YOUR_CLIENT_ID\",\n\tClientSecret: \"YOUR_CLIENT_SECRET\",\n\tScope:        \"https://www.googleapis.com/auth/buzz\",\n\tAuthURL:      \"https://accounts.google.com/o/oauth2/auth\",\n\tTokenURL:     \"https://accounts.google.com/o/oauth2/token\",\n\tRedirectURL:  \"http://you.example.org/handler\",\n}\n\n// A landing page redirects to the OAuth provider to get the auth code.\nfunc landing(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, config.AuthCodeURL(\"foo\"), http.StatusFound)\n}\n\n// The user will be redirected back to this handler, that takes the\n// \"code\" query parameter and Exchanges it for an access token.\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tt := &oauth2.Transport{Config: config}\n\tt.Exchange(r.FormValue(\"code\"))\n\t// The Transport now has a valid Token. Create an *http.Client\n\t// with which we can make authenticated API requests.\n\tc := t.Client()\n\n\t// Now you can pass the authenticated Client to gopencils, and\n\t// it will be used to make all the requests\n\tapi := gopencils.Api(\"http://your-api-url.com/api/\", c)\n\n\t// Create a pointer to our response struct, which will hold the response\n\tre := &respStruct{}\n\t// Maybe some payload to send along with the request?\n\tpayload := map[string]interface{}{\"Key1\": \"Value1\"}\n\n\t// Perform a GET request\n\t// URL Requested: http://your-api-url.com/api/users\n\tapi.Res(\"users\", re).Get()\n\n\t// Perform a GET request with Querystring\n\tquerystring := map[string]string{\"page\": \"100\"}\n\t// URL Requested: http://your-api-url.com/api/users/123/items?page=100\n\tapi.Res(\"users\").Id(123).Res(\"items\", re).Get(querystring)\n\n\t// Or perform a POST Request\n\t// URL Requested: http://your-api-url.com/api/items/123 with payload as json Data\n\tapi.Res(\"items\", re).Id(123).Post(payload)\n}\n"
  },
  {
    "path": "resource.go",
    "content": "// Copyright 2014 Vadim Kravcenko\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"): you may\n// not use this file except in compliance with the License. You may obtain\n// a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n// License for the specific language governing permissions and limitations\n// under the License.\n\n// Gopencils is a Golang REST Client with which you can easily consume REST API's. Supported Response formats: JSON\npackage gopencils\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n)\n\nvar ErrCantUseAsQuery = errors.New(\"can't use options[0] as Query\")\n\n// Resource is basically an url relative to given API Baseurl.\ntype Resource struct {\n\tApi         *ApiStruct\n\tUrl         string\n\tid          string\n\tQueryValues url.Values\n\tPayload     io.Reader\n\tHeaders     http.Header\n\tResponse    interface{}\n\tRaw         *http.Response\n}\n\n// Creates a new Resource.\nfunc (r *Resource) Res(options ...interface{}) *Resource {\n\tif len(options) > 0 {\n\t\tvar url string\n\t\tif len(r.Url) > 0 {\n\t\t\turl = r.Url + \"/\" + options[0].(string)\n\t\t} else {\n\t\t\turl = options[0].(string)\n\t\t}\n\n\t\theader := r.Headers\n\t\tif header == nil {\n\t\t\theader = http.Header{}\n\t\t}\n\t\tnewR := &Resource{Url: url, Api: r.Api, Headers: header}\n\n\t\tif len(options) > 1 {\n\t\t\tnewR.Response = options[1]\n\t\t}\n\n\t\treturn newR\n\t}\n\treturn r\n}\n\n// Same as Res() Method, but returns a Resource with url resource/:id\nfunc (r *Resource) Id(options ...interface{}) *Resource {\n\tif len(options) > 0 {\n\t\tid := \"\"\n\t\tswitch v := options[0].(type) {\n\t\tdefault:\n\t\t\tid = v.(string)\n\t\tcase int:\n\t\t\tid = strconv.Itoa(v)\n\t\tcase int64:\n\t\t\tid = strconv.FormatInt(v, 10)\n\t\t}\n\t\turl := r.Url + \"/\" + id\n\t\theader := r.Headers\n\t\tif header == nil {\n\t\t\theader = http.Header{}\n\t\t}\n\t\tnewR := &Resource{id: id, Url: url, Api: r.Api, Headers: header, Response: &r.Response}\n\n\t\tif len(options) > 1 {\n\t\t\tnewR.Response = options[1]\n\t\t}\n\t\treturn newR\n\t}\n\treturn r\n}\n\n// Sets QueryValues for current Resource\nfunc (r *Resource) SetQuery(querystring map[string]string) *Resource {\n\tr.QueryValues = make(url.Values)\n\tfor k, v := range querystring {\n\t\tr.QueryValues.Set(k, v)\n\t}\n\treturn r\n}\n\n// Performs a GET request on given Resource\n// Accepts map[string]string as parameter, will be used as querystring.\nfunc (r *Resource) Get(options ...interface{}) (*Resource, error) {\n\tif len(options) > 0 {\n\t\tif qry, ok := options[0].(map[string]string); ok {\n\t\t\tr.SetQuery(qry)\n\t\t} else {\n\t\t\treturn nil, ErrCantUseAsQuery\n\t\t}\n\n\t}\n\treturn r.do(\"GET\")\n}\n\n// Performs a HEAD request on given Resource\n// Accepts map[string]string as parameter, will be used as querystring.\nfunc (r *Resource) Head(options ...interface{}) (*Resource, error) {\n\tif len(options) > 0 {\n\t\tif qry, ok := options[0].(map[string]string); ok {\n\t\t\tr.SetQuery(qry)\n\t\t} else {\n\t\t\treturn nil, ErrCantUseAsQuery\n\t\t}\n\t}\n\treturn r.do(\"HEAD\")\n}\n\n// Performs a PUT request on given Resource.\n// Accepts interface{} as parameter, will be used as payload.\nfunc (r *Resource) Put(options ...interface{}) (*Resource, error) {\n\tif len(options) > 0 {\n\t\tr.Payload = r.SetPayload(options[0])\n\t}\n\treturn r.do(\"PUT\")\n}\n\n// Performs a POST request on given Resource.\n// Accepts interface{} as parameter, will be used as payload.\nfunc (r *Resource) Post(options ...interface{}) (*Resource, error) {\n\tif len(options) > 0 {\n\t\tr.Payload = r.SetPayload(options[0])\n\t}\n\treturn r.do(\"POST\")\n}\n\n// Performs a Delete request on given Resource.\n// Accepts map[string]string as parameter, will be used as querystring.\nfunc (r *Resource) Delete(options ...interface{}) (*Resource, error) {\n\tif len(options) > 0 {\n\t\tif qry, ok := options[0].(map[string]string); ok {\n\t\t\tr.SetQuery(qry)\n\t\t} else {\n\t\t\treturn nil, ErrCantUseAsQuery\n\t\t}\n\t}\n\treturn r.do(\"DELETE\")\n}\n\n// Performs a Delete request on given Resource.\n// Accepts map[string]string as parameter, will be used as querystring.\nfunc (r *Resource) Options(options ...interface{}) (*Resource, error) {\n\tif len(options) > 0 {\n\t\tif qry, ok := options[0].(map[string]string); ok {\n\t\t\tr.SetQuery(qry)\n\t\t} else {\n\t\t\treturn nil, ErrCantUseAsQuery\n\t\t}\n\t}\n\treturn r.do(\"OPTIONS\")\n}\n\n// Performs a PATCH request on given Resource.\n// Accepts interface{} as parameter, will be used as payload.\nfunc (r *Resource) Patch(options ...interface{}) (*Resource, error) {\n\tif len(options) > 0 {\n\t\tr.Payload = r.SetPayload(options[0])\n\t}\n\treturn r.do(\"PATCH\")\n}\n\n// Main method, opens the connection, sets basic auth, applies headers,\n// parses response json.\nfunc (r *Resource) do(method string) (*Resource, error) {\n\turl := *r.Api.BaseUrl\n\tif len(url.Path) > 0 {\n\t\turl.Path += \"/\" + r.Url\n\t} else {\n\t\turl.Path = r.Url\n\t}\n\tif r.Api.PathSuffix != \"\" {\n\t\turl.Path += r.Api.PathSuffix\n\t}\n\n\turl.RawQuery = r.QueryValues.Encode()\n\treq, err := http.NewRequest(method, url.String(), r.Payload)\n\tif err != nil {\n\t\treturn r, err\n\t}\n\n\tif r.Api.BasicAuth != nil {\n\t\treq.SetBasicAuth(r.Api.BasicAuth.Username, r.Api.BasicAuth.Password)\n\t}\n\n\tif r.Headers != nil {\n\t\tfor k, _ := range r.Headers {\n\t\t\treq.Header.Set(k, r.Headers.Get(k))\n\t\t}\n\t}\n\n\tresp, err := r.Api.Client.Do(req)\n\tif err != nil {\n\t\treturn r, err\n\t}\n\n\tr.Raw = resp\n\n\tif resp.StatusCode >= 400 {\n\t\treturn r, nil\n\t}\n\n\tfor k, _ := range r.Raw.Header {\n\t\tr.SetHeader(k, r.Raw.Header.Get(k));\n\t}\n\n\tdefer resp.Body.Close()\n\n\terr = json.NewDecoder(resp.Body).Decode(r.Response)\n\tif err != nil {\n\t\treturn r, err\n\t}\n\n\treturn r, nil\n}\n\n// Sets Payload for current Resource\nfunc (r *Resource) SetPayload(args interface{}) io.Reader {\n\tvar b []byte\n\tb, _ = json.Marshal(args)\n\tr.SetHeader(\"Content-Type\", \"application/json\")\n\treturn bytes.NewBuffer(b)\n}\n\n// Sets Headers\nfunc (r *Resource) SetHeader(key string, value string) {\n\tr.Headers.Add(key, value)\n}\n\n// Overwrites the client that will be used for requests.\n// For example if you want to use your own client with OAuth2\nfunc (r *Resource) SetClient(c *http.Client) {\n\tr.Api.Client = c\n}\n"
  },
  {
    "path": "resource_test.go",
    "content": "package gopencils\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\ttestMux *http.ServeMux\n\ttestSrv *httptest.Server\n)\n\nfunc init() {\n\ttestMux = http.NewServeMux()\n\ttestSrv = httptest.NewServer(testMux)\n}\n\ntype respStruct struct {\n\tLogin   string\n\tId      int\n\tName    string\n\tMessage string\n}\ntype httpbinResponse struct {\n\tArgs    string\n\tHeaders map[string]string\n\tUrl     string\n\tJson    map[string]interface{}\n}\n\nfunc TestResouceUrl(t *testing.T) {\n\tapi := Api(\"https://test-url.com\")\n\tassert.Equal(t, api.Api.BaseUrl.String(), \"https://test-url.com\",\n\t\t\"Parsed Url Should match\")\n\tapi.SetQuery(map[string]string{\"key1\": \"value1\", \"key2\": \"value2\"})\n\tassert.Equal(t, api.QueryValues.Encode(), \"key1=value1&key2=value2\",\n\t\t\"Parsed QueryString Url Should match\")\n\tassert.Equal(t, api.Url, \"\", \"Base Url Should be empty\")\n}\n\nfunc TestCanUsePathInResourceUrl(t *testing.T) {\n\ttestMux.HandleFunc(\"/path/to/api/resname/id123\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tfmt.Fprintln(rw, `{\"Test\":\"Okay\"}`)\n\t\t})\n\n\tres := Api(testSrv.URL+\"/path/to/api\", nil)\n\n\tvar resp struct {\n\t\tTest string\n\t}\n\n\t_, err := res.Res(\"resname\").Id(\"id123\", &resp).Get()\n\tassert.Nil(t, err, \"err should be nil\")\n\tassert.Equal(t, \"Okay\", resp.Test, \"resp shoul be Okay\")\n}\n\nfunc TestCanUseAuthForApi(t *testing.T) {\n\tapi := Api(\"https://test-url.com\", &BasicAuth{\"username\", \"password\"})\n\tassert.Equal(t, api.Api.BasicAuth.Username, \"username\",\n\t\t\"Username should match\")\n\tassert.Equal(t, api.Api.BasicAuth.Password, \"password\",\n\t\t\"Password should match\")\n}\n\nfunc TestCanGetResource(t *testing.T) {\n\t// github stubs\n\ttestMux.HandleFunc(\"/users/bndr\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tfmt.Fprintln(rw, readJson(\"_tests/github_bndr.json\"))\n\t\t})\n\ttestMux.HandleFunc(\"/users/torvalds\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tfmt.Fprintln(rw, readJson(\"_tests/github_torvalds.json\"))\n\t\t})\n\n\tapi := Api(testSrv.URL)\n\t// Users endpoint\n\tusers := api.Res(\"users\")\n\n\tusernames := []string{\"bndr\", \"torvalds\"}\n\n\tfor _, username := range usernames {\n\t\t// Create a new pointer to response Struct\n\t\tr := new(respStruct)\n\t\t// Get user with id i into the newly created response struct\n\t\t_, err := users.Id(username, r).Get()\n\t\tif err != nil {\n\t\t\tt.Log(\"Error Getting Data from Test API\\nErr:\", err)\n\t\t} else {\n\t\t\tassert.Equal(t, r.Message, \"\", \"Error message must be empty\")\n\t\t\tassert.Equal(t, r.Login, username, \"Username should be equal\")\n\t\t}\n\t}\n\tresp := new(respStruct)\n\tapi.Res(\"users\", resp).Id(\"bndr\").Get()\n\tassert.Equal(t, resp.Login, \"bndr\")\n\tresp2 := new(respStruct)\n\tapi.Res(\"users\").Id(\"bndr\", resp2).Get()\n\tassert.Equal(t, resp2.Login, \"bndr\")\n}\n\nfunc TestCanCreateResource(t *testing.T) {\n\ttestMux.HandleFunc(\"/post\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tassert.Equal(t, req.Method, \"POST\", \"unexpected Method\")\n\t\t\tassert.Equal(t, req.URL.Path, \"/post\", \"unexpected Path\")\n\t\t\tassert.Equal(t, req.Header.Get(\"Content-Type\"), \"application/json\",\n\t\t\t\t\"Expected json content type\")\n\t\t\tfmt.Fprintln(rw, readJson(\"_tests/common_response.json\"))\n\t\t})\n\n\tapi := Api(testSrv.URL)\n\tpayload := map[string]interface{}{\"Key\": \"Value1\"}\n\tr := new(httpbinResponse)\n\tapi.Res(\"post\", r).Post(payload)\n\tassert.Equal(t, r.Json[\"Key\"], \"Value1\", \"Payload must match\")\n}\n\nfunc TestCanPutResource(t *testing.T) {\n\ttestMux.HandleFunc(\"/put\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tassert.Equal(t, req.Method, \"PUT\", \"unexpected Method\")\n\t\t\tassert.Equal(t, req.URL.Path, \"/put\", \"unexpected Path\")\n\t\t\tassert.Equal(t, req.Header.Get(\"Content-Type\"), \"application/json\",\n\t\t\t\t\"Expected json content type\")\n\t\t\tfmt.Fprintln(rw, readJson(\"_tests/common_response.json\"))\n\t\t})\n\n\tapi := Api(testSrv.URL)\n\tpayload := map[string]interface{}{\"Key\": \"Value1\"}\n\tr := new(httpbinResponse)\n\tapi.Res(\"put\", r).Put(payload)\n\tassert.Equal(t, r.Json[\"Key\"], \"Value1\", \"Payload must match\")\n}\n\nfunc TestCanDeleteResource(t *testing.T) {\n\ttestMux.HandleFunc(\"/delete\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tassert.Equal(t, req.Method, \"DELETE\", \"unexpected Method\")\n\t\t\tassert.Equal(t, req.URL.Path, \"/delete\", \"unexpected Path\")\n\t\t\tfmt.Fprintln(rw, readJson(\"_tests/delete_response.json\"))\n\t\t})\n\n\tapi := Api(testSrv.URL)\n\tr := new(httpbinResponse)\n\tapi.Id(\"delete\", r).Delete()\n\tassert.Equal(t, r.Url, \"https://httpbin.org/delete\", \"Url must match\")\n}\n\nfunc TestPathSuffix(t *testing.T) {\n\ttestMux.HandleFunc(\"/item/32.json\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tassert.Equal(t, req.Method, \"GET\", \"unexpected Method\")\n\t\t\tassert.Equal(t, req.URL.Path, \"/item/32.json\", \"unexpected Path\")\n\t\t\tfmt.Fprintln(rw, readJson(\"_tests/common_response.json\"))\n\t\t})\n\n\tapi := Api(testSrv.URL, \".json\")\n\tr := new(httpbinResponse)\n\tapi.Res(\"item\", r).Id(32).Get()\n\tassert.Equal(t, r.Json[\"Key\"], \"Value1\", \"Payload must match\")\n}\n\nfunc TestPathSuffixWithQueryParam(t *testing.T) {\n\ttestMux.HandleFunc(\"/item/42.json\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\tassert.Equal(t, req.Method, \"GET\", \"unexpected Method\")\n\t\t\tassert.Equal(t, req.URL.Path, \"/item/42.json\", \"unexpected Path\")\n\t\t\tassert.Equal(t, req.URL.Query().Get(\"param\"), \"test\", \"unexpected QueryParam\")\n\t\t\tfmt.Fprintln(rw, readJson(\"_tests/common_response.json\"))\n\t\t})\n\n\tapi := Api(testSrv.URL, \".json\")\n\tr := new(httpbinResponse)\n\tapi.Res(\"item\", r).Id(42).Get(map[string]string{\"param\": \"test\"})\n\tassert.Equal(t, r.Json[\"Key\"], \"Value1\", \"Payload must match\")\n}\n\nfunc TestResourceId(t *testing.T) {\n\tapi := Api(\"https://test-url.com\")\n\tassert.Equal(t, api.Res(\"users\").Id(\"test\").Url, \"users/test\",\n\t\t\"Url should match\")\n\tassert.Equal(t, api.Res(\"users\").Id(123).Res(\"items\").Id(111).Url,\n\t\t\"users/123/items/111\", \"Multilevel Url should match\")\n\tassert.Equal(t, api.Res(\"users\").Id(int64(9223372036854775807)).Url, \"users/9223372036854775807\",\n\t\t\"int64 id should work\")\n}\n\nfunc TestDoNotDecodeBodyOnErr(t *testing.T) {\n\ttests := []int{\n\t\t400, 401, 500, 501,\n\t}\n\n\tactualData := strings.TrimSpace(readJson(\"_tests/error.json\"))\n\n\t// will be changed later\n\tcode := 0\n\ttestMux.HandleFunc(\"/error\",\n\t\tfunc(rw http.ResponseWriter, req *http.Request) {\n\t\t\trw.WriteHeader(code)\n\t\t\tfmt.Fprintln(rw, actualData)\n\t\t})\n\n\tapi := Api(testSrv.URL)\n\n\tfor _, code = range tests {\n\t\tresp := make(map[string]interface{})\n\t\tr, err := api.Id(\"error\", &resp).Get()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tassert.Equal(t, map[string]interface{}{}, resp,\n\t\t\tfmt.Sprintf(\"response should be unparsed: %d\", code))\n\n\t\trespData, err := ioutil.ReadAll(r.Raw.Body)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tassert.Equal(t, actualData, strings.TrimSpace(string(respData)),\n\t\t\tfmt.Sprintf(\"response body is not accessible: %d\", code))\n\t}\n}\n\nfunc readJson(path string) string {\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(buf)\n}\n"
  }
]