quest

package module
v0.0.0-...-679f61b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 7, 2015 License: MIT Imports: 21 Imported by: 2

README

quest

build status GoDoc

quest is an elegant HTTP networking library written in Go. Alamofire inspired.

Features

  • Chainable Request / Response methods
  • URL / JSON / Parameter Encoding
  • Progress Tracking
  • Upload File / Data / Stream
  • Download using Request
  • Authentication
  • Timeout, defaults to 30 * time.Second
  • cURL Debug Output
  • TLS config
  • Support Short APIS Get, Post, Patch, Put, Delete
  • Pipe Stream to other request
  • Download Resume data
  • More Errors Output
  • HTTP Response Validation
  • Comprehensive Unit Test Coverage
  • Complete Documentation

Usage

Making a Request
import "github.com/go-libs/quest"

q, err := quest.Request("GET", "http://httpbin.org/get")
Response Handling
q, err := quest.Request(quest.GET, "http://httpbin.org/get")
q.
  Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, e error) {
  log.Println(req)
  log.Println(res)
  log.Println(data)
  log.Println(err)
})
Response Serialization

Built-in Response Methods

  • Response(func(*http.Request, *http.Response, *bytes.Buffer, error))
  • ResponseBytes(func(*http.Request, *http.Response, []byte, error))
  • ResponseString(func(*http.Request, *http.Response, string, error))
  • ResponseJSON(f interface{}), f Must be func
    • func(req *http.Request, res *http.Response, data *JSONStruct, e error)
    • func(req *http.Request, res *http.Response, data JSONStruct, e error)
Response String Handler
q, _ := quest.Request(quest.GET, "http://httpbin.org/get")
q.ResponseString(func(req *http.Request, res *http.Response, data string, e error) {
  log.Println(data)
})
Response JSON Handler
type DataStruct struct {
  Headers map[string]string
  Origin  string
}

q, _ := quest.Request(quest.GET, "http://httpbin.org/get")
q.ResponseJSON(func(req *http.Request, res *http.Response, data DataStruct, e error) {
  log.Println(data)
})

q.ResponseJSON(func(req *http.Request, res *http.Response, data *DataStruct, e error) {
  log.Println(data)
})
Chained Response Handlers

Response handlers can even be chained:

q, _ := quest.Request(quest.GET, "http://httpbin.org/get")
q.
  ResponseString(func(req *http.Request, res *http.Response, data string, e error) {
  log.Println(data)
}).
  ResponseJSON(func(req *http.Request, res *http.Response, data *DataStruct, e error) {
  log.Println(data)
})
HTTP Methods
OPTIONS
GET
HEAD
POST
PUT
PATCH
DELETE
TRACE
CONNECT
Query String
type Options struct {
  Foo string `url:"foo"`
}

q, _ := quest.Request(quest.GET, "http://httpbin.org/get")
q.Query(Options{"bar"})
// http://httpbin.org/get?foo=bar
POST Request with JSON-encoded Parameters
type PostParameters struct {
  Foo []int             `json:"foo,omitempty"`
  Bar map[string]string `json:"bar,omitempty"`
}

parameters := PostParameters{
  "foo": []int{1, 2, 3},
  "bar": map[string]string{"baz": "qux"},
}

type DataStruct struct {
  Headers map[string]string
  Origin  string
  Json    PostParameters `json:"json,omitempty"`
}

type OtherDataStruct struct {
  Headers map[string]string
  Origin  string
}

q, _ := quest.Request(quest.POST, "http://httpbin.org/post")
q.Encoding("JSON").
  Parameters(&parameters).
  ResponseJSON(func(req *http.Request, res *http.Response, data *DataStruct, e error) {
  log.Println(data)
}).
  ResponseJSON(func(req *http.Request, res *http.Response, data OtherDataStruct, e error) {
  log.Println(data)
})
Downloading
Downloading a File
q, _ := quest.Download(quest.GET, "http://httpbin.org/stream/100", "stream.log")
q.Do()
Downloading a File w/Progress
destination := "tmp/stream.log"
q, _ := quest.Download(quest.GET, "http://httpbin.org/bytes/1024", destination)
q.
  Progress(func(bytesRead, totalBytesRead, totalBytesExpectedToRead int64) {
    log.Println(bytesRead, totalBytesRead, totalBytesExpectedToRead)
  }).Do()

destination, _ := os.Create("tmp/stream2.log")
q, _ := quest.Download(quest.GET, "http://httpbin.org/bytes/10240", destination)
q.
  Progress(func(current, total, expected int64) {
    log.Println(current, total, expected)
  }).Response(func(request *http.Request, response *http.Response, data *bytes.Buffer, err error) {
    log.Println(data.Len())
  })
Uploading
Supported Upload Types
  • File
  • Data
  • Stream
Uploading a File
q, _: = quest.Upload(quest.POST, "http://httpbin.org/post", map[string]string{"stream": "tmp/stream.log"})
q.Do()
Uploading multi files w/Progress
stream2, _ := os.Open("tmp/stream2.log")
stream3 := bytes.NewBufferString(`Hello Quest!`)
data := map[string]interface{}{
  "stream1": "tmp/stream.log",      // filepath or filename
  "stream2": stream2,               // *os.File
  "stream3": stream3,               // io.Reader, filename is fieldname `stream3`
}

q, _ := quest.Upload(quest.POST, "http://httpbin.org/post", data)
q.
  Progress(func(current, total, expected int64) {
    log.Println(current, total, expected)
  }).Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
    log.Println(data.Len())
  })
Authenticate
HTTP Basic Authentication
type Auth struct {
  User          string
  Passwd        string
  Authenticated bool
}
user := "user"
passwd := "password"

q, _ := quest.Request(quest.GET, "https://httpbin.org/basic-auth/"+user+"/"+passwd)
q.Authenticate(user, passwd).
  ResponseJSON(func(_ *http.Request, _ *http.Response, data Auth, _ error) {
  log.Println(data)
}).Do()
Timeout
s := time.Duration(3 * time.Second)
q, _ := quest.Request(quest.GET, "https://httpbin.org/delay/5")
q.Timeout(s).Do()
Println & DebugPrintln Request
q, _ := Request(GET, "http://httpbin.org/cookies")
log.Println(q.Println())
c := &http.Cookie{}
c.Name = "k"
c.Value = "v"
q, _ := Request(GET, "http://httpbin.org/cookies")
q.Query(&queryParams)
q.Cookie(c)
log.Println(q.DebugPrintln())
Response Bytes(), String(), JSON(v interface{})
q, _ := Request(GET, "http://httpbin.org/get")
b1, err := q.Bytes()
s1, err := q.String()

type DataStruct struct {
  Headers map[string]string
  Origin  string
}

v := DataStruct{}
err := q.JSON(&v)
TLS client config TLSConfig(*tls.Config)
t := &tls.Config{}
q, _ := Request(GET, "http://httpbin.org/get")
q.TLSConfig(t)
Get() Post() Put() Patch() Delete() Short APIs
q, _ = Get("http://httpbin.org/get")

License

MIT

Documentation

Index

Constants

View Source
const (
	OPTIONS = "OPTIONS"
	GET     = "GET"
	HEAD    = "HEAD"
	POST    = "POST"
	PUT     = "PUT"
	PATCH   = "PATCH"
	DELETE  = "DELETE"
	TRACE   = "TRACE"
	CONNECT = "CONNECT"
)

Methods.

HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3

Variables

Method map.

Functions

func QueryString

func QueryString(options interface{}) (qs string, err error)

Types

type BytesHandlerFunc

type BytesHandlerFunc func(*http.Request, *http.Response, []byte, error)

type HandlerFunc

type HandlerFunc func(*http.Request, *http.Response, *bytes.Buffer, error)

type Requester

type Requester struct {
	// HTTP method
	Method string

	// Base URL for Requests.
	Endpoint string
	Url      *url.URL

	Header http.Header
	Body   io.ReadCloser
	Length int64

	StatusCode int

	Buffer *bytes.Buffer

	// Upload
	IsUpload bool

	// Download
	IsDownload bool
	// contains filtered or unexported fields
}

A Request manages communication with http service.

func Delete

func Delete(endpoint string) (*Requester, error)

Delete Request

func Download

func Download(method, endpoint string, destination interface{}) (r *Requester, err error)

download file / data / stream to file

func Get

func Get(endpoint string) (*Requester, error)

Get Request

func Patch

func Patch(endpoint string) (*Requester, error)

Patch Request

func Post

func Post(endpoint string) (*Requester, error)

Post Request

func Put

func Put(endpoint string) (*Requester, error)

Put Request

func Request

func Request(method, endpoint string) (r *Requester, err error)

base request client

func Upload

func Upload(method, endpoint string, files map[string]interface{}) (r *Requester, err error)

upload file / data / stream

func (*Requester) Authenticate

func (r *Requester) Authenticate(username, password string) *Requester

func (*Requester) Bytes

func (r *Requester) Bytes() ([]byte, error)

func (*Requester) Cancel

func (r *Requester) Cancel()

func (*Requester) Cookie

func (r *Requester) Cookie(cookies ...*http.Cookie) *Requester

func (*Requester) DebugPrintln

func (r *Requester) DebugPrintln() string

func (*Requester) Destination

func (r *Requester) Destination(destination interface{}) *Requester

func (*Requester) Do

func (r *Requester) Do() (*bytes.Buffer, error)

func (*Requester) Encoding

func (r *Requester) Encoding(t string) *Requester

func (*Requester) Files

func (r *Requester) Files(files map[string]interface{}) *Requester

func (*Requester) Form

func (r *Requester) Form(files map[string]interface{}, fields map[string]string) *Requester

func (*Requester) JSON

func (r *Requester) JSON(v interface{}) (err error)

func (*Requester) Parameters

func (r *Requester) Parameters(data interface{}) *Requester

func (*Requester) Pipe

func (r *Requester) Pipe()

func (*Requester) Println

func (r *Requester) Println() string

func (*Requester) Progress

func (r *Requester) Progress(f progress.HandlerFunc) *Requester

func (*Requester) Query

func (r *Requester) Query(data interface{}) *Requester

func (*Requester) Response

func (r *Requester) Response(handler HandlerFunc) *Requester

func (*Requester) ResponseBytes

func (r *Requester) ResponseBytes(handler BytesHandlerFunc) *Requester

func (*Requester) ResponseJSON

func (r *Requester) ResponseJSON(f interface{}) *Requester

func (*Requester) ResponseString

func (r *Requester) ResponseString(handler StringHandlerFunc) *Requester

func (*Requester) Set

func (r *Requester) Set(key, value string) *Requester

func (*Requester) String

func (r *Requester) String() (string, error)

func (*Requester) TLSConfig

func (r *Requester) TLSConfig(t *tls.Config) *Requester

func (*Requester) Timeout

func (r *Requester) Timeout(t time.Duration) *Requester

func (*Requester) ValidateStatusCode

func (r *Requester) ValidateStatusCode(statusCodes ...int) (b bool)

Status Code

type StringHandlerFunc

type StringHandlerFunc func(*http.Request, *http.Response, string, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL