Simple http client

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())    
    
Similar Resources

Enriches the standard go http client with retry functionality.

httpRetry Enriches the standard go http client with retry functionality using a wrapper around the Roundtripper interface. The advantage of this libra

Dec 10, 2022

http client for golang

http client for golang

Request HTTP client for golang, Inspired by Javascript-axios Python-request. If you have experience about axios or requests, you will love it. No 3rd

Dec 18, 2022

A nicer interface for golang stdlib HTTP client

rq A nicer interface for golang stdlib HTTP client Documents rq: here client: here jar: here Why? Because golang HTTP client is a pain in the a... Fea

Dec 12, 2022

A Go HTTP client library for creating and sending API requests

A Go HTTP client library for creating and sending API requests

Sling Sling is a Go HTTP client library for creating and sending API requests. Slings store HTTP Request properties to simplify sending requests and d

Jan 7, 2023

a Go HTTP client with timeouts

go-httpclient requires Go 1.1+ as of v0.4.0 the API has been completely re-written for Go 1.1 (for a Go 1.0.x compatible release see 1adef50) Provides

Nov 10, 2022

GoRequest -- Simplified HTTP client ( inspired by nodejs SuperAgent )

GoRequest -- Simplified HTTP client ( inspired by nodejs SuperAgent )

GoRequest GoRequest -- Simplified HTTP client ( inspired by famous SuperAgent lib in Node.js ) "Shooting Requests like a Machine Gun" - Gopher Sending

Jan 1, 2023

gout to become the Swiss Army Knife of the http client @^^@--- gout 是http client领域的瑞士军刀,小巧,强大,犀利。具体用法可看文档,如使用迷惑或者API用得不爽都可提issues

gout to become the Swiss Army Knife of the http client @^^@--->  gout 是http client领域的瑞士军刀,小巧,强大,犀利。具体用法可看文档,如使用迷惑或者API用得不爽都可提issues

gout gout 是go写的http 客户端,为提高工作效率而开发 构架 feature 支持设置 GET/PUT/DELETE/PATH/HEAD/OPTIONS 支持设置请求 http header(可传 struct,map,array,slice 等类型) 支持设置 URL query(可

Dec 29, 2022

Retry, Race, All, Some, etc strategies for http.Client calls

reqstrategy Package reqstrategy provides functions for coordinating http.Client calls. It wraps typical call strategies like making simultaneous reque

Apr 30, 2021

An enhanced HTTP client for Go

An enhanced HTTP client for Go

Heimdall Description Installation Usage Making a simple GET request Creating a hystrix-like circuit breaker Creating a hystrix-like circuit breaker wi

Jan 2, 2023
Comments
  • Minor code improvements

    Minor code improvements

    • Improved codestyle, for example, removed empty lines where they should not be, added where they should be
    • Removed some commented code
    • Removed pass-by-reference where it is not compulsory
    • Minor naming changes, for example, quoteEscaper renamed to quoteEscapists because it's more correct form imho
Speak HTTP like a local. (the simple, intuitive HTTP console, golang version)

http-gonsole This is the Go port of the http-console. Speak HTTP like a local Talking to an HTTP server with curl can be fun, but most of the time it'

Jul 14, 2021
Simple HTTP package that wraps net/http

Simple HTTP package that wraps net/http

Jan 17, 2022
Http-conection - A simple example of how to establish a HTTP connection using Golang

A simple example of how to establish a HTTP connection using Golang

Feb 1, 2022
Simple HTTP and REST client library for Go

Resty Simple HTTP and REST client library for Go (inspired by Ruby rest-client) Features section describes in detail about Resty capabilities Resty Co

Jan 1, 2023
Simple http client

www Simple http client for golang with user-friendly interface. Features Chainable API Direct file upload Timeout Cookie GZIP Charset detection Cleane

Nov 15, 2021
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

fasthttp Fast HTTP implementation for Go. Currently fasthttp is successfully used by VertaMedia in a production serving up to 200K rps from more than

Jan 2, 2023
NATS HTTP Round Tripper - This is a Golang http.RoundTripper that uses NATS as a transport.

This is a Golang http.RoundTripper that uses NATS as a transport. Included is a http.RoundTripper for clients, a server that uses normal HTTP Handlers and any existing http handler mux and a Caddy Server transport.

Dec 6, 2022
Full-featured, plugin-driven, extensible HTTP client toolkit for Go

gentleman Full-featured, plugin-driven, middleware-oriented toolkit to easily create rich, versatile and composable HTTP clients in Go. gentleman embr

Dec 23, 2022
An enhanced http client for Golang
An enhanced http client for Golang

go-http-client An enhanced http client for Golang Documentation on go.dev ?? This package provides you a http client package for your http requests. Y

Dec 23, 2022
An enhanced HTTP client for Go
An enhanced HTTP client for Go

Heimdall Description Installation Usage Making a simple GET request Creating a hystrix-like circuit breaker Creating a hystrix-like circuit breaker wi

Jan 9, 2023