Full Code of bndr/gopencils for AI

master 22e283ad7611 cached
16 files
35.9 KB
9.7k tokens
37 symbols
1 requests
Download .txt
Repository: bndr/gopencils
Branch: master
Commit: 22e283ad7611
Files: 16
Total size: 35.9 KB

Directory structure:
gitextract_5pt5i19o/

├── .gitignore
├── .travis.yml
├── AUTHOR
├── CONTRIBUTORS
├── LICENSE.md
├── README.md
├── _tests/
│   ├── common_response.json
│   ├── delete_response.json
│   ├── error.json
│   ├── github_bndr.json
│   └── github_torvalds.json
├── api.go
├── examples/
│   ├── example_basic_auth.go
│   └── example_oauth.go
├── resource.go
└── resource_test.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so

# Folders
_obj
_test

# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out

*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*

_testmain.go

*.exe
*.test
*.prof

gopencils

================================================
FILE: .travis.yml
================================================
language: go

go:
  - 1.2
  - 1.3
  - tip
install:
  - go get github.com/stretchr/testify/assert
  - go get golang.org/x/oauth2


================================================
FILE: AUTHOR
================================================
Vadim Kravcenko 2014

================================================
FILE: CONTRIBUTORS
================================================
# Contributors: git log --format='%aN <%aE>' | sort -uf
bndr <bndrzz@gmail.com>
Henry <cryptix@riseup.net>
Stanislav Seletskiy <s.seletskiy@gmail.com>
Vadim Kravcenko <bndrzz@gmail.com>


================================================
FILE: LICENSE.md
================================================
Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: README.md
================================================
# Gopencils - Dynamically consume REST APIs
[![GoDoc](https://godoc.org/github.com/bndr/gopencils?status.svg)](https://godoc.org/github.com/bndr/gopencils)
[![Build Status](https://travis-ci.org/bndr/gopencils.svg?branch=master)](https://travis-ci.org/bndr/gopencils)

## Summary
Gopencils is a REST Client written in go. Easily consume any REST API's. Supported Response formats: JSON

## Install

    go get github.com/bndr/gopencils

## Simple to use

Gopencils was designed to help you easily make requests to REST APIs without much hassle. It supports both Basic-Auth as well as OAuth.

Example Basic-Auth

```go

type UserExample struct {
	Id            string
	Name          string
	Origin        string
	Url           string
	SomeJsonField string
}
// Create Basic Auth
auth := gopencils.BasicAuth{"username", "password"}

// Create New Api with our auth
api := gopencils.Api("http://your-api-url.com/api/", &auth)

// Create a pointer to our response struct
resp := &UserExample{}

// Perform a GET request
// URL Requested: http://your-api-url.com/api/users/1
api.Res("users", resp).Id(1).Get()

// Get Single Item
api.Res("users", resp).Id(1).Get()

// Perform a GET request with Querystring
querystring := map[string]string{"page": "100", "per_page": "1000"}

// URL Requested: http://your-api-url.com/api/users/123/items?page=100&per_page=1000
resource := api.Res("users").Id(123).Res("items", resp).Get(querystring)

// Now resp contains the returned json object
// resource.Raw contains raw http response,

// You can supply Path suffix to the api which will be applied to every url
// e.g /items/id.json
api := gopencils.Api("http://your-api-url.com/api/", &auth, ".json")

```

Example Github Api

```go

package main

import (
	"fmt"
	"github.com/bndr/gopencils"
)

type respStruct struct {
	Login string
	Id    int
	Name  string
}

func main() {
	api := gopencils.Api("https://api.github.com")
	// Users Resource
	users := api.Res("users")

	usernames := []string{"bndr", "torvalds", "coleifer"}

	for _, username := range usernames {
		// Create a new pointer to response Struct
		r := new(respStruct)
		// Get user with id i into the newly created response struct
		_, err := users.Id(username, r).Get()
		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(r)
		}
	}
}
```
More examples in the examples folder.

## Why?
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.

## Is it ready?

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.

## Contribute

All Contributions are welcome. The todo list is on the bottom of this README. Feel free to send a pull request.

## License

Apache License 2.0

## TODO
1. Add more Options (Flexibility)
2. Support XML Response
3. Better Error Handling


================================================
FILE: _tests/common_response.json
================================================
{
  "args": {},
  "data": "{\"Key\":\"Value1\"}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Connection": "close",
    "Content-Length": "16",
    "Content-Type": "application/json",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.37.0",
    "X-Request-Id": "6268bee8-2ea0-4144-802a-6166fe18d84f"
  },
  "json": {
    "Key": "Value1"
  },
  "origin": "95.91.230.168",
  "url": "https://httpbin.org/post"
}


================================================
FILE: _tests/delete_response.json
================================================
{
  "args": {},
  "data": "",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Connection": "close",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.37.0",
    "X-Request-Id": "b29e2435-926f-4fb4-bd1d-ec1b179e1523"
  },
  "json": null,
  "origin": "95.91.230.168",
  "url": "https://httpbin.org/delete"
}


================================================
FILE: _tests/error.json
================================================
{
  "message": "some error occured",
  "code": "E1234"
}


================================================
FILE: _tests/github_bndr.json
================================================
{
  "login": "bndr",
  "id": 1145456,
  "avatar_url": "https://avatars.githubusercontent.com/u/1145456?",
  "gravatar_id": "8d05db0b0b8b74d5a0f93d0b1db22909",
  "url": "https://api.github.com/users/bndr",
  "html_url": "https://github.com/bndr",
  "followers_url": "https://api.github.com/users/bndr/followers",
  "following_url": "https://api.github.com/users/bndr/following{/other_user}",
  "gists_url": "https://api.github.com/users/bndr/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/bndr/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/bndr/subscriptions",
  "organizations_url": "https://api.github.com/users/bndr/orgs",
  "repos_url": "https://api.github.com/users/bndr/repos",
  "events_url": "https://api.github.com/users/bndr/events{/privacy}",
  "received_events_url": "https://api.github.com/users/bndr/received_events",
  "type": "User",
  "site_admin": false,
  "name": "Vadim Kravcenko",
  "company": "",
  "blog": "http://vadimkravcenko.com",
  "location": "Germany",
  "email": "bndrzz@gmail.com",
  "hireable": false,
  "bio": null,
  "public_repos": 17,
  "public_gists": 2,
  "followers": 13,
  "following": 0,
  "created_at": "2011-10-22T19:21:17Z",
  "updated_at": "2014-07-20T10:24:25Z"
}


================================================
FILE: _tests/github_torvalds.json
================================================
{
  "login": "torvalds",
  "id": 1024025,
  "avatar_url": "https://avatars.githubusercontent.com/u/1024025?",
  "gravatar_id": "fb47627bc8c0bcdb36321edfbf02e916",
  "url": "https://api.github.com/users/torvalds",
  "html_url": "https://github.com/torvalds",
  "followers_url": "https://api.github.com/users/torvalds/followers",
  "following_url": "https://api.github.com/users/torvalds/following{/other_user}",
  "gists_url": "https://api.github.com/users/torvalds/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/torvalds/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/torvalds/subscriptions",
  "organizations_url": "https://api.github.com/users/torvalds/orgs",
  "repos_url": "https://api.github.com/users/torvalds/repos",
  "events_url": "https://api.github.com/users/torvalds/events{/privacy}",
  "received_events_url": "https://api.github.com/users/torvalds/received_events",
  "type": "User",
  "site_admin": false,
  "name": "Linus Torvalds",
  "company": "Linux Foundation",
  "blog": null,
  "location": "Portland, OR",
  "email": null,
  "hireable": false,
  "bio": null,
  "public_repos": 2,
  "public_gists": 0,
  "followers": 17605,
  "following": 0,
  "created_at": "2011-09-03T15:26:22Z",
  "updated_at": "2014-07-20T10:27:30Z"
}


================================================
FILE: api.go
================================================
// Copyright 2014 Vadim Kravcenko
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

package gopencils

import (
	"crypto/tls"
	"net/http"
	"net/http/cookiejar"
	"net/url"
)

// Basic Auth
type BasicAuth struct {
	Username string
	Password string
}

// Main Api Instance.
// No Options yet supported.
type ApiStruct struct {
	BaseUrl    *url.URL
	BasicAuth  *BasicAuth
	Client     *http.Client
	Cookies    *cookiejar.Jar
	PathSuffix string
}

// Create a new API Instance and returns a Resource
// Accepts URL as parameter, and either a Basic Auth or a OAuth2 Client.
func Api(baseUrl string, options ...interface{}) *Resource {
	u, err := url.Parse(baseUrl)
	if err != nil {
		// TODO: don't panic..
		panic("Api() - url.Parse(baseUrl) Error:" + err.Error())
	}

	apiInstance := &ApiStruct{BaseUrl: u, BasicAuth: nil}

	for _, o := range options {
		switch v := o.(type) {
		case *BasicAuth:
			apiInstance.BasicAuth = v
		case *http.Client:
			apiInstance.Client = v
		case string:
			apiInstance.PathSuffix = v
		}
	}

	if apiInstance.Client == nil {
		apiInstance.Cookies, _ = cookiejar.New(nil)

		// Skip verify by default?
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}

		client := &http.Client{
			Transport: tr,
			Jar:       apiInstance.Cookies,
		}
		apiInstance.Client = client
	}
	return &Resource{Url: "", Api: apiInstance}
}


================================================
FILE: examples/example_basic_auth.go
================================================
package main

import (
	"github.com/bndr/gopencils"
)

func main() {
	// Create Basic Auth
	auth := gopencils.BasicAuth{"username", "password"}
	// Create New Api with our auth
	api := gopencils.Api("http://your-api-url.com/api/", &auth)

	// Maybe some payload to send along with the request?
	payload := map[string]interface{}{"Key": "Value1"}
	resp := new(respStruct)
	// Perform a GET request
	// URL Requested: http://your-api-url.com/api/users
	api.Res("users", &respStruct{}).Get()

	// Get Single Item
	api.Res("users", &respStruct{}).Id(1).Get()

	// Perform a GET request with Querystring
	querystring := map[string]string{"page": "100", "per_page": "1000"}
	// URL Requested: http://your-api-url.com/api/users/123/items?page=100&per_page=1000
	api.Res("users").Id(123).Res("items", resp).Get(querystring)

	// Or perform a POST Request
	// URL Requested: http://your-api-url.com/api/items/123 with payload as json Data
	api.Res("items", resp).Id(123).Post(payload)

	// Users endpoint
	users := api.Res("users")

	for i := 0; i < 10; i++ {
		// Create a new pointer to response Struct
		user := new(respStruct)
		// Get user with id i into the newly created response struct
		users.Id(i, user).Get()
	}

}


================================================
FILE: examples/example_oauth.go
================================================
package main

import (
	"golang.org/x/oauth2"
	"github.com/bndr/gopencils"
	"net/http"
)

// Oauth example taken from https://godoc.org/code.google.com/p/goauth2/oauth
// The authenticated client must be passed to gopencils for OAuth to work.

type respStruct struct {
	Args          map[string]string
	Headers       map[string]string
	Origin        string
	Url           string
	Authorization string
}

// Specify your configuration. (typically as a global variable)
var config = &oauth2.Config{
	ClientId:     "YOUR_CLIENT_ID",
	ClientSecret: "YOUR_CLIENT_SECRET",
	Scope:        "https://www.googleapis.com/auth/buzz",
	AuthURL:      "https://accounts.google.com/o/oauth2/auth",
	TokenURL:     "https://accounts.google.com/o/oauth2/token",
	RedirectURL:  "http://you.example.org/handler",
}

// A landing page redirects to the OAuth provider to get the auth code.
func landing(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, config.AuthCodeURL("foo"), http.StatusFound)
}

// The user will be redirected back to this handler, that takes the
// "code" query parameter and Exchanges it for an access token.
func handler(w http.ResponseWriter, r *http.Request) {
	t := &oauth2.Transport{Config: config}
	t.Exchange(r.FormValue("code"))
	// The Transport now has a valid Token. Create an *http.Client
	// with which we can make authenticated API requests.
	c := t.Client()

	// Now you can pass the authenticated Client to gopencils, and
	// it will be used to make all the requests
	api := gopencils.Api("http://your-api-url.com/api/", c)

	// Create a pointer to our response struct, which will hold the response
	re := &respStruct{}
	// Maybe some payload to send along with the request?
	payload := map[string]interface{}{"Key1": "Value1"}

	// Perform a GET request
	// URL Requested: http://your-api-url.com/api/users
	api.Res("users", re).Get()

	// Perform a GET request with Querystring
	querystring := map[string]string{"page": "100"}
	// URL Requested: http://your-api-url.com/api/users/123/items?page=100
	api.Res("users").Id(123).Res("items", re).Get(querystring)

	// Or perform a POST Request
	// URL Requested: http://your-api-url.com/api/items/123 with payload as json Data
	api.Res("items", re).Id(123).Post(payload)
}


================================================
FILE: resource.go
================================================
// Copyright 2014 Vadim Kravcenko
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

// Gopencils is a Golang REST Client with which you can easily consume REST API's. Supported Response formats: JSON
package gopencils

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/url"
	"strconv"
)

var ErrCantUseAsQuery = errors.New("can't use options[0] as Query")

// Resource is basically an url relative to given API Baseurl.
type Resource struct {
	Api         *ApiStruct
	Url         string
	id          string
	QueryValues url.Values
	Payload     io.Reader
	Headers     http.Header
	Response    interface{}
	Raw         *http.Response
}

// Creates a new Resource.
func (r *Resource) Res(options ...interface{}) *Resource {
	if len(options) > 0 {
		var url string
		if len(r.Url) > 0 {
			url = r.Url + "/" + options[0].(string)
		} else {
			url = options[0].(string)
		}

		header := r.Headers
		if header == nil {
			header = http.Header{}
		}
		newR := &Resource{Url: url, Api: r.Api, Headers: header}

		if len(options) > 1 {
			newR.Response = options[1]
		}

		return newR
	}
	return r
}

// Same as Res() Method, but returns a Resource with url resource/:id
func (r *Resource) Id(options ...interface{}) *Resource {
	if len(options) > 0 {
		id := ""
		switch v := options[0].(type) {
		default:
			id = v.(string)
		case int:
			id = strconv.Itoa(v)
		case int64:
			id = strconv.FormatInt(v, 10)
		}
		url := r.Url + "/" + id
		header := r.Headers
		if header == nil {
			header = http.Header{}
		}
		newR := &Resource{id: id, Url: url, Api: r.Api, Headers: header, Response: &r.Response}

		if len(options) > 1 {
			newR.Response = options[1]
		}
		return newR
	}
	return r
}

// Sets QueryValues for current Resource
func (r *Resource) SetQuery(querystring map[string]string) *Resource {
	r.QueryValues = make(url.Values)
	for k, v := range querystring {
		r.QueryValues.Set(k, v)
	}
	return r
}

// Performs a GET request on given Resource
// Accepts map[string]string as parameter, will be used as querystring.
func (r *Resource) Get(options ...interface{}) (*Resource, error) {
	if len(options) > 0 {
		if qry, ok := options[0].(map[string]string); ok {
			r.SetQuery(qry)
		} else {
			return nil, ErrCantUseAsQuery
		}

	}
	return r.do("GET")
}

// Performs a HEAD request on given Resource
// Accepts map[string]string as parameter, will be used as querystring.
func (r *Resource) Head(options ...interface{}) (*Resource, error) {
	if len(options) > 0 {
		if qry, ok := options[0].(map[string]string); ok {
			r.SetQuery(qry)
		} else {
			return nil, ErrCantUseAsQuery
		}
	}
	return r.do("HEAD")
}

// Performs a PUT request on given Resource.
// Accepts interface{} as parameter, will be used as payload.
func (r *Resource) Put(options ...interface{}) (*Resource, error) {
	if len(options) > 0 {
		r.Payload = r.SetPayload(options[0])
	}
	return r.do("PUT")
}

// Performs a POST request on given Resource.
// Accepts interface{} as parameter, will be used as payload.
func (r *Resource) Post(options ...interface{}) (*Resource, error) {
	if len(options) > 0 {
		r.Payload = r.SetPayload(options[0])
	}
	return r.do("POST")
}

// Performs a Delete request on given Resource.
// Accepts map[string]string as parameter, will be used as querystring.
func (r *Resource) Delete(options ...interface{}) (*Resource, error) {
	if len(options) > 0 {
		if qry, ok := options[0].(map[string]string); ok {
			r.SetQuery(qry)
		} else {
			return nil, ErrCantUseAsQuery
		}
	}
	return r.do("DELETE")
}

// Performs a Delete request on given Resource.
// Accepts map[string]string as parameter, will be used as querystring.
func (r *Resource) Options(options ...interface{}) (*Resource, error) {
	if len(options) > 0 {
		if qry, ok := options[0].(map[string]string); ok {
			r.SetQuery(qry)
		} else {
			return nil, ErrCantUseAsQuery
		}
	}
	return r.do("OPTIONS")
}

// Performs a PATCH request on given Resource.
// Accepts interface{} as parameter, will be used as payload.
func (r *Resource) Patch(options ...interface{}) (*Resource, error) {
	if len(options) > 0 {
		r.Payload = r.SetPayload(options[0])
	}
	return r.do("PATCH")
}

// Main method, opens the connection, sets basic auth, applies headers,
// parses response json.
func (r *Resource) do(method string) (*Resource, error) {
	url := *r.Api.BaseUrl
	if len(url.Path) > 0 {
		url.Path += "/" + r.Url
	} else {
		url.Path = r.Url
	}
	if r.Api.PathSuffix != "" {
		url.Path += r.Api.PathSuffix
	}

	url.RawQuery = r.QueryValues.Encode()
	req, err := http.NewRequest(method, url.String(), r.Payload)
	if err != nil {
		return r, err
	}

	if r.Api.BasicAuth != nil {
		req.SetBasicAuth(r.Api.BasicAuth.Username, r.Api.BasicAuth.Password)
	}

	if r.Headers != nil {
		for k, _ := range r.Headers {
			req.Header.Set(k, r.Headers.Get(k))
		}
	}

	resp, err := r.Api.Client.Do(req)
	if err != nil {
		return r, err
	}

	r.Raw = resp

	if resp.StatusCode >= 400 {
		return r, nil
	}

	for k, _ := range r.Raw.Header {
		r.SetHeader(k, r.Raw.Header.Get(k));
	}

	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(r.Response)
	if err != nil {
		return r, err
	}

	return r, nil
}

// Sets Payload for current Resource
func (r *Resource) SetPayload(args interface{}) io.Reader {
	var b []byte
	b, _ = json.Marshal(args)
	r.SetHeader("Content-Type", "application/json")
	return bytes.NewBuffer(b)
}

// Sets Headers
func (r *Resource) SetHeader(key string, value string) {
	r.Headers.Add(key, value)
}

// Overwrites the client that will be used for requests.
// For example if you want to use your own client with OAuth2
func (r *Resource) SetClient(c *http.Client) {
	r.Api.Client = c
}


================================================
FILE: resource_test.go
================================================
package gopencils

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

var (
	testMux *http.ServeMux
	testSrv *httptest.Server
)

func init() {
	testMux = http.NewServeMux()
	testSrv = httptest.NewServer(testMux)
}

type respStruct struct {
	Login   string
	Id      int
	Name    string
	Message string
}
type httpbinResponse struct {
	Args    string
	Headers map[string]string
	Url     string
	Json    map[string]interface{}
}

func TestResouceUrl(t *testing.T) {
	api := Api("https://test-url.com")
	assert.Equal(t, api.Api.BaseUrl.String(), "https://test-url.com",
		"Parsed Url Should match")
	api.SetQuery(map[string]string{"key1": "value1", "key2": "value2"})
	assert.Equal(t, api.QueryValues.Encode(), "key1=value1&key2=value2",
		"Parsed QueryString Url Should match")
	assert.Equal(t, api.Url, "", "Base Url Should be empty")
}

func TestCanUsePathInResourceUrl(t *testing.T) {
	testMux.HandleFunc("/path/to/api/resname/id123",
		func(rw http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(rw, `{"Test":"Okay"}`)
		})

	res := Api(testSrv.URL+"/path/to/api", nil)

	var resp struct {
		Test string
	}

	_, err := res.Res("resname").Id("id123", &resp).Get()
	assert.Nil(t, err, "err should be nil")
	assert.Equal(t, "Okay", resp.Test, "resp shoul be Okay")
}

func TestCanUseAuthForApi(t *testing.T) {
	api := Api("https://test-url.com", &BasicAuth{"username", "password"})
	assert.Equal(t, api.Api.BasicAuth.Username, "username",
		"Username should match")
	assert.Equal(t, api.Api.BasicAuth.Password, "password",
		"Password should match")
}

func TestCanGetResource(t *testing.T) {
	// github stubs
	testMux.HandleFunc("/users/bndr",
		func(rw http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(rw, readJson("_tests/github_bndr.json"))
		})
	testMux.HandleFunc("/users/torvalds",
		func(rw http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(rw, readJson("_tests/github_torvalds.json"))
		})

	api := Api(testSrv.URL)
	// Users endpoint
	users := api.Res("users")

	usernames := []string{"bndr", "torvalds"}

	for _, username := range usernames {
		// Create a new pointer to response Struct
		r := new(respStruct)
		// Get user with id i into the newly created response struct
		_, err := users.Id(username, r).Get()
		if err != nil {
			t.Log("Error Getting Data from Test API\nErr:", err)
		} else {
			assert.Equal(t, r.Message, "", "Error message must be empty")
			assert.Equal(t, r.Login, username, "Username should be equal")
		}
	}
	resp := new(respStruct)
	api.Res("users", resp).Id("bndr").Get()
	assert.Equal(t, resp.Login, "bndr")
	resp2 := new(respStruct)
	api.Res("users").Id("bndr", resp2).Get()
	assert.Equal(t, resp2.Login, "bndr")
}

func TestCanCreateResource(t *testing.T) {
	testMux.HandleFunc("/post",
		func(rw http.ResponseWriter, req *http.Request) {
			assert.Equal(t, req.Method, "POST", "unexpected Method")
			assert.Equal(t, req.URL.Path, "/post", "unexpected Path")
			assert.Equal(t, req.Header.Get("Content-Type"), "application/json",
				"Expected json content type")
			fmt.Fprintln(rw, readJson("_tests/common_response.json"))
		})

	api := Api(testSrv.URL)
	payload := map[string]interface{}{"Key": "Value1"}
	r := new(httpbinResponse)
	api.Res("post", r).Post(payload)
	assert.Equal(t, r.Json["Key"], "Value1", "Payload must match")
}

func TestCanPutResource(t *testing.T) {
	testMux.HandleFunc("/put",
		func(rw http.ResponseWriter, req *http.Request) {
			assert.Equal(t, req.Method, "PUT", "unexpected Method")
			assert.Equal(t, req.URL.Path, "/put", "unexpected Path")
			assert.Equal(t, req.Header.Get("Content-Type"), "application/json",
				"Expected json content type")
			fmt.Fprintln(rw, readJson("_tests/common_response.json"))
		})

	api := Api(testSrv.URL)
	payload := map[string]interface{}{"Key": "Value1"}
	r := new(httpbinResponse)
	api.Res("put", r).Put(payload)
	assert.Equal(t, r.Json["Key"], "Value1", "Payload must match")
}

func TestCanDeleteResource(t *testing.T) {
	testMux.HandleFunc("/delete",
		func(rw http.ResponseWriter, req *http.Request) {
			assert.Equal(t, req.Method, "DELETE", "unexpected Method")
			assert.Equal(t, req.URL.Path, "/delete", "unexpected Path")
			fmt.Fprintln(rw, readJson("_tests/delete_response.json"))
		})

	api := Api(testSrv.URL)
	r := new(httpbinResponse)
	api.Id("delete", r).Delete()
	assert.Equal(t, r.Url, "https://httpbin.org/delete", "Url must match")
}

func TestPathSuffix(t *testing.T) {
	testMux.HandleFunc("/item/32.json",
		func(rw http.ResponseWriter, req *http.Request) {
			assert.Equal(t, req.Method, "GET", "unexpected Method")
			assert.Equal(t, req.URL.Path, "/item/32.json", "unexpected Path")
			fmt.Fprintln(rw, readJson("_tests/common_response.json"))
		})

	api := Api(testSrv.URL, ".json")
	r := new(httpbinResponse)
	api.Res("item", r).Id(32).Get()
	assert.Equal(t, r.Json["Key"], "Value1", "Payload must match")
}

func TestPathSuffixWithQueryParam(t *testing.T) {
	testMux.HandleFunc("/item/42.json",
		func(rw http.ResponseWriter, req *http.Request) {
			assert.Equal(t, req.Method, "GET", "unexpected Method")
			assert.Equal(t, req.URL.Path, "/item/42.json", "unexpected Path")
			assert.Equal(t, req.URL.Query().Get("param"), "test", "unexpected QueryParam")
			fmt.Fprintln(rw, readJson("_tests/common_response.json"))
		})

	api := Api(testSrv.URL, ".json")
	r := new(httpbinResponse)
	api.Res("item", r).Id(42).Get(map[string]string{"param": "test"})
	assert.Equal(t, r.Json["Key"], "Value1", "Payload must match")
}

func TestResourceId(t *testing.T) {
	api := Api("https://test-url.com")
	assert.Equal(t, api.Res("users").Id("test").Url, "users/test",
		"Url should match")
	assert.Equal(t, api.Res("users").Id(123).Res("items").Id(111).Url,
		"users/123/items/111", "Multilevel Url should match")
	assert.Equal(t, api.Res("users").Id(int64(9223372036854775807)).Url, "users/9223372036854775807",
		"int64 id should work")
}

func TestDoNotDecodeBodyOnErr(t *testing.T) {
	tests := []int{
		400, 401, 500, 501,
	}

	actualData := strings.TrimSpace(readJson("_tests/error.json"))

	// will be changed later
	code := 0
	testMux.HandleFunc("/error",
		func(rw http.ResponseWriter, req *http.Request) {
			rw.WriteHeader(code)
			fmt.Fprintln(rw, actualData)
		})

	api := Api(testSrv.URL)

	for _, code = range tests {
		resp := make(map[string]interface{})
		r, err := api.Id("error", &resp).Get()
		if err != nil {
			t.Fatal(err)
		}

		assert.Equal(t, map[string]interface{}{}, resp,
			fmt.Sprintf("response should be unparsed: %d", code))

		respData, err := ioutil.ReadAll(r.Raw.Body)
		if err != nil {
			t.Fatal(err)
		}

		assert.Equal(t, actualData, strings.TrimSpace(string(respData)),
			fmt.Sprintf("response body is not accessible: %d", code))
	}
}

func readJson(path string) string {
	buf, err := ioutil.ReadFile(path)
	if err != nil {
		panic(err)
	}

	return string(buf)
}
Download .txt
gitextract_5pt5i19o/

├── .gitignore
├── .travis.yml
├── AUTHOR
├── CONTRIBUTORS
├── LICENSE.md
├── README.md
├── _tests/
│   ├── common_response.json
│   ├── delete_response.json
│   ├── error.json
│   ├── github_bndr.json
│   └── github_torvalds.json
├── api.go
├── examples/
│   ├── example_basic_auth.go
│   └── example_oauth.go
├── resource.go
└── resource_test.go
Download .txt
SYMBOL INDEX (37 symbols across 5 files)

FILE: api.go
  type BasicAuth (line 25) | type BasicAuth struct
  type ApiStruct (line 32) | type ApiStruct struct
  function Api (line 42) | func Api(baseUrl string, options ...interface{}) *Resource {

FILE: examples/example_basic_auth.go
  function main (line 7) | func main() {

FILE: examples/example_oauth.go
  type respStruct (line 12) | type respStruct struct
  function landing (line 31) | func landing(w http.ResponseWriter, r *http.Request) {
  function handler (line 37) | func handler(w http.ResponseWriter, r *http.Request) {

FILE: resource.go
  type Resource (line 31) | type Resource struct
    method Res (line 43) | func (r *Resource) Res(options ...interface{}) *Resource {
    method Id (line 68) | func (r *Resource) Id(options ...interface{}) *Resource {
    method SetQuery (line 95) | func (r *Resource) SetQuery(querystring map[string]string) *Resource {
    method Get (line 105) | func (r *Resource) Get(options ...interface{}) (*Resource, error) {
    method Head (line 119) | func (r *Resource) Head(options ...interface{}) (*Resource, error) {
    method Put (line 132) | func (r *Resource) Put(options ...interface{}) (*Resource, error) {
    method Post (line 141) | func (r *Resource) Post(options ...interface{}) (*Resource, error) {
    method Delete (line 150) | func (r *Resource) Delete(options ...interface{}) (*Resource, error) {
    method Options (line 163) | func (r *Resource) Options(options ...interface{}) (*Resource, error) {
    method Patch (line 176) | func (r *Resource) Patch(options ...interface{}) (*Resource, error) {
    method do (line 185) | func (r *Resource) do(method string) (*Resource, error) {
    method SetPayload (line 238) | func (r *Resource) SetPayload(args interface{}) io.Reader {
    method SetHeader (line 246) | func (r *Resource) SetHeader(key string, value string) {
    method SetClient (line 252) | func (r *Resource) SetClient(c *http.Client) {

FILE: resource_test.go
  function init (line 19) | func init() {
  type respStruct (line 24) | type respStruct struct
  type httpbinResponse (line 30) | type httpbinResponse struct
  function TestResouceUrl (line 37) | func TestResouceUrl(t *testing.T) {
  function TestCanUsePathInResourceUrl (line 47) | func TestCanUsePathInResourceUrl(t *testing.T) {
  function TestCanUseAuthForApi (line 64) | func TestCanUseAuthForApi(t *testing.T) {
  function TestCanGetResource (line 72) | func TestCanGetResource(t *testing.T) {
  function TestCanCreateResource (line 109) | func TestCanCreateResource(t *testing.T) {
  function TestCanPutResource (line 126) | func TestCanPutResource(t *testing.T) {
  function TestCanDeleteResource (line 143) | func TestCanDeleteResource(t *testing.T) {
  function TestPathSuffix (line 157) | func TestPathSuffix(t *testing.T) {
  function TestPathSuffixWithQueryParam (line 171) | func TestPathSuffixWithQueryParam(t *testing.T) {
  function TestResourceId (line 186) | func TestResourceId(t *testing.T) {
  function TestDoNotDecodeBodyOnErr (line 196) | func TestDoNotDecodeBodyOnErr(t *testing.T) {
  function readJson (line 233) | func readJson(path string) string {
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (40K chars).
[
  {
    "path": ".gitignore",
    "chars": 276,
    "preview": "# 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 spe"
  },
  {
    "path": ".travis.yml",
    "chars": 128,
    "preview": "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"
  },
  {
    "path": "AUTHOR",
    "chars": 20,
    "preview": "Vadim Kravcenko 2014"
  },
  {
    "path": "CONTRIBUTORS",
    "chars": 186,
    "preview": "# Contributors: git log --format='%aN <%aE>' | sort -uf\nbndr <bndrzz@gmail.com>\nHenry <cryptix@riseup.net>\nStanislav Sel"
  },
  {
    "path": "LICENSE.md",
    "chars": 11323,
    "preview": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licens"
  },
  {
    "path": "README.md",
    "chars": 2942,
    "preview": "# Gopencils - Dynamically consume REST APIs\n[![GoDoc](https://godoc.org/github.com/bndr/gopencils?status.svg)](https://g"
  },
  {
    "path": "_tests/common_response.json",
    "chars": 438,
    "preview": "{\n  \"args\": {},\n  \"data\": \"{\\\"Key\\\":\\\"Value1\\\"}\",\n  \"files\": {},\n  \"form\": {},\n  \"headers\": {\n    \"Accept\": \"*/*\",\n    \""
  },
  {
    "path": "_tests/delete_response.json",
    "chars": 331,
    "preview": "{\n  \"args\": {},\n  \"data\": \"\",\n  \"files\": {},\n  \"form\": {},\n  \"headers\": {\n    \"Accept\": \"*/*\",\n    \"Connection\": \"close\""
  },
  {
    "path": "_tests/error.json",
    "chars": 57,
    "preview": "{\n  \"message\": \"some error occured\",\n  \"code\": \"E1234\"\n}\n"
  },
  {
    "path": "_tests/github_bndr.json",
    "chars": 1260,
    "preview": "{\n  \"login\": \"bndr\",\n  \"id\": 1145456,\n  \"avatar_url\": \"https://avatars.githubusercontent.com/u/1145456?\",\n  \"gravatar_id"
  },
  {
    "path": "_tests/github_torvalds.json",
    "chars": 1293,
    "preview": "{\n  \"login\": \"torvalds\",\n  \"id\": 1024025,\n  \"avatar_url\": \"https://avatars.githubusercontent.com/u/1024025?\",\n  \"gravata"
  },
  {
    "path": "api.go",
    "chars": 1890,
    "preview": "// Copyright 2014 Vadim Kravcenko\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"): you may\n// not u"
  },
  {
    "path": "examples/example_basic_auth.go",
    "chars": 1217,
    "preview": "package main\n\nimport (\n\t\"github.com/bndr/gopencils\"\n)\n\nfunc main() {\n\t// Create Basic Auth\n\tauth := gopencils.BasicAuth{"
  },
  {
    "path": "examples/example_oauth.go",
    "chars": 2251,
    "preview": "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 ht"
  },
  {
    "path": "resource.go",
    "chars": 6190,
    "preview": "// Copyright 2014 Vadim Kravcenko\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"): you may\n// not u"
  },
  {
    "path": "resource_test.go",
    "chars": 6932,
    "preview": "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/str"
  }
]

About this extraction

This page contains the full source code of the bndr/gopencils GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (35.9 KB), approximately 9.7k tokens, and a symbol index with 37 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!