www

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2021 License: MIT Imports: 19 Imported by: 0

README

www

Simple http client for golang with user-friendly interface.

Features

  • Chainable API
  • Direct file upload
  • Timeout
  • Cookie
  • GZIP
  • Charset detection
  • Cleaned http client

Installation

go get github.com/GarryGaller/go-www

Quick Start

package main

import (
    "fmt"
    "net/url"

    "github.com/GarryGaller/go-www"
)

func main() {
    client := www.NewClient()
    req := www.NewRequest(client)
    resp := req.WithQuery(&url.Values{"key": {"value"}}).
        Get("https://httpbin.org/get")

    if resp.Error() != nil {
        fmt.Printf("%v", resp.Error())
    } else {
        fmt.Printf("%s\n", resp.Status)
        fmt.Printf("%s\n", resp.Text())
    }

    // or cleaned client and request in one step
    resp = www.New().
        WithQuery(&url.Values{"key": {"value"}}).
        Get("https://httpbin.org/get")

    fmt.Printf("%s\n", resp.Status)
    fmt.Printf("%s\n", resp.Text())
}

Usage

Client types

// returns a new http.Client with similar default values to http.Client, but with a non-shared 
// Transport, idle connections disabled, and keepalives disabled.
cleanedClient := www.Cleaned()

//returns a new http.Client with similar default values to
// http.Client, but with a shared Transport. Do not use this function for
// transient clients as it can leak file descriptors over time. Only use this
// for clients that will be re-used for the same host(s).
sharedClient := www.Pooled()

// standard client &http.Client{}
defaultClient := www.Default()

// hand over your client or  or will be used &http.Client{}
client := www.NewClient(...)

// Returns the request object along with the cleaned client
req := www.New()
Sending Request
// get
req.Get("https://httpbin.org/get")

// get with query and headers
req.WithQuery(&url.Values{
        "q": []string{"go", "generics"}})
        .Get("https://httpbin.org/get", 
            http.Header{"User-Agent": {"Mozilla"}},
        )

// post
req.WithForm(&url.Values{"token": {"123456"}}).
    Post("https://httpbin.org/post")

// post file as data
req.WithFile(MustOpen(filePath), "text/plain; charset=utf-8").
    Post("https://httpbin.org/post")

// post file as multipart
req.AttachFile(MustOpen(filePath)).
    Post("https://httpbin.org/post"

// post files(multipart)
req.AttachFiles(map[string]interface{}{
    "file":  {MustOpen(filePath), "text/plain; charset=utf-8"},
    "file2": {MustOpen(filePath2),"text/plain; charset=utf-8"},
    "other": {strings.NewReader("hello world!")},
    }).Post("https://httpbin.org/post")

// delete
req.Delete("http://httpbin.org/delete")

// patch
req.Head("http://httpbin.org/patch")

// put
req.Put("http://httpbin.org/put")

Customize Client and Request

Before starting a new HTTP request, you can specify additional client options and add a query string or form data to the request object as well as new headers. The client object can be used by sharing it between other requests.

client := www.NewClient()
client.WithTimeout(2 * time.Second)
jar, _ := cookiejar.New(nil)
client.WithJar(jar)
fmt.Printf("%s\n", client.Timeout)
fmt.Printf("%#v\n", client.Jar)

client = www.Cleaned().With(2 *time.Second, jar)
fmt.Printf("%s\n", client.Timeout)
fmt.Printf("%#v\n", client.Jar)

req := www.NewRequest(client)
req.WithQuery(&url.Values{"q": {"generics"}, "l":{"go"}, "type":{"topics"}})
resp := req.Get("https://github.com/search",
        http.Header{
             "User-Agent": {"Mozilla"},
            //"Accept": {"application/vnd.github.v3+json"},
            //"Authorization": {"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}},
        })
fmt.Printf("%s\n", resp.Status)
fmt.Printf("%s\n", resp.Headers())
Response

The www.Response is a thin wrap of http.Response.


// response as text
resp = www.Get("https://httpbin.org/get")
bodyAsString = resp.Text()

// response as bytes
resp = www.Get("https://httpbin.org/get")
bodyAsBytes = resp.Content()

// response as map[key]interface{}
resp = www.WithJson(params).Post("https://httpbin.org/post")
bodyAsMap = resp.Json()

Error Checking

req := NewRequest(client)
if req.Error() != nil {
    fmt.Printf("%v\n", req.Error())
}

resp := req.Get("https://httpbin.org/get")
if resp.Error() != nil {
    fmt.Printf("%v\n", resp.Error())
}
Handle Cookies
// cookies
req.SetCookies(&http.Cookie{
                Name:   "token",
                Value:  "some_token",
                MaxAge: 300,
    }).Get("https://httpbin.org/cookies")
    
fmt.Printf("%s\n", req.Cookies())    
    

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrorEmptyListValues = errors.New("An empty list of values is passed to create multipart content")

Functions

func CreateFormFile added in v0.2.0

func CreateFormFile(w *multipart.Writer,
	fieldname, filename string,
	contentType ...string) (io.Writer, error)

func MustOpen

func MustOpen(f string) *os.File

Types

type ClientOptions

type ClientOptions map[string]interface{}

func (*ClientOptions) Merge

func (opt *ClientOptions) Merge(other ClientOptions)

type LeveledLogger added in v0.2.1

type LeveledLogger interface {
	Error(msg string, keysAndValues ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Debug(msg string, keysAndValues ...interface{})
	Warn(msg string, keysAndValues ...interface{})
}

type Logger added in v0.2.1

type Logger interface {
	Printf(string, ...interface{})
}

type Request

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

func New

func New() *Request

func NewRequest

func NewRequest(client *StandardClient) *Request

func (*Request) AttachFile

func (r *Request) AttachFile(reader io.Reader, contentType ...string) *Request

func (*Request) AttachFiles

func (r *Request) AttachFiles(files map[string][]interface{}) *Request

func (*Request) Connect

func (r *Request) Connect(uri string) *Response

func (*Request) Cookies

func (r *Request) Cookies() (out []*http.Cookie)

func (*Request) Delete

func (r *Request) Delete(uri string, headers ...http.Header) *Response

func (*Request) Do

func (r *Request) Do(method string,
	uri string, headers ...http.Header) *Response

func (*Request) Error

func (r *Request) Error() error

func (*Request) Get

func (r *Request) Get(uri string, headers ...http.Header) *Response

func (*Request) Head

func (r *Request) Head(uri string) *Response

func (*Request) Headers

func (r *Request) Headers() (out http.Header)

func (*Request) JSON added in v0.2.0

func (r *Request) JSON(data interface{}) *Request

func (*Request) Json added in v0.2.0

func (r *Request) Json(data interface{}) *Request

func (*Request) Options

func (r *Request) Options(uri string) *Response

func (*Request) Patch

func (r *Request) Patch(uri string, headers ...http.Header) *Response

func (*Request) Post

func (r *Request) Post(
	uri string, headers ...http.Header) *Response

func (*Request) Put

func (r *Request) Put(uri string, headers ...http.Header) *Response

func (*Request) SetCookies

func (r *Request) SetCookies(cookies ...*http.Cookie) *Request

func (*Request) Trace

func (r *Request) Trace(uri string) *Response

func (*Request) With

func (r *Request) With(params *url.Values, data *url.Values) *Request

func (*Request) WithFile

func (r *Request) WithFile(reader io.Reader) *Request

func (*Request) WithForm

func (r *Request) WithForm(data *url.Values) *Request

func (*Request) WithQuery

func (r *Request) WithQuery(params *url.Values) *Request

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

func (*Response) Charset added in v0.2.0

func (resp *Response) Charset(contentTypes ...string) (charset string)

func (*Response) Content

func (resp *Response) Content() []byte

func (*Response) ContentType added in v0.2.0

func (resp *Response) ContentType(contentTypes ...string) (mime, charset string)

func (*Response) DetectCodePage added in v0.2.0

func (resp *Response) DetectCodePage() string

func (*Response) Error

func (resp *Response) Error() error

func (*Response) Headers

func (resp *Response) Headers() http.Header

func (*Response) JSON added in v0.2.0

func (resp *Response) JSON() (data map[string]interface{})

func (*Response) Json

func (resp *Response) Json() (data map[string]interface{})

func (*Response) Mime added in v0.2.0

func (resp *Response) Mime(contentTypes ...string) (mime string)

func (*Response) NewReader added in v0.2.0

func (resp *Response) NewReader() (reader io.Reader)

func (*Response) Text

func (resp *Response) Text() string

type StandardClient added in v0.2.0

type StandardClient struct {
	*http.Client
	Logger interface{}
	// contains filtered or unexported fields
}

func Cleaned added in v0.2.0

func Cleaned() (cl *StandardClient)

func Default added in v0.2.0

func Default() (cl *StandardClient)

func NewClient

func NewClient(clients ...*http.Client) (cl *StandardClient)

func Pooled added in v0.2.0

func Pooled() (cl *StandardClient)

func (*StandardClient) Cookies added in v0.2.0

func (client *StandardClient) Cookies(host string) []*http.Cookie

func (*StandardClient) Error added in v0.2.0

func (client *StandardClient) Error() error

func (*StandardClient) LLog added in v0.2.1

func (cl *StandardClient) LLog() LeveledLogger

func (*StandardClient) Log added in v0.2.1

func (cl *StandardClient) Log() Logger

func (*StandardClient) SLog added in v0.2.1

func (cl *StandardClient) SLog() StandardLogger

func (*StandardClient) SetCookies added in v0.2.0

func (client *StandardClient) SetCookies(
	host string, cookies ...*http.Cookie) *StandardClient

func (*StandardClient) With added in v0.2.0

func (client *StandardClient) With(options ...interface{}) *StandardClient

func (*StandardClient) WithJar added in v0.2.0

func (client *StandardClient) WithJar(jar http.CookieJar) *StandardClient

func (*StandardClient) WithLogger added in v0.2.1

func (client *StandardClient) WithLogger(logger Logger) *StandardClient

func (*StandardClient) WithTimeout added in v0.2.0

func (client *StandardClient) WithTimeout(
	timeout time.Duration) *StandardClient

func (*StandardClient) WithTransport added in v0.2.0

func (client *StandardClient) WithTransport(
	transport http.RoundTripper) *StandardClient

type StandardLogger added in v0.2.1

type StandardLogger interface {
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Fatalln(v ...interface{})
	Flags() int
	Output(calldepth int, s string) error
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
	Panicln(v ...interface{})
	Prefix() string
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
	SetFlags(flag int)
	SetOutput(w io.Writer)
	SetPrefix(prefix string)
	Writer() io.Writer
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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