Skip to content

API: send an HTTP request by method chaining #23

@wenchy

Description

@wenchy

Design goal

  • Simple and easy to understand API name
  • Auto deduce body type by generics (type parameters)
  • Optional Context (also support Timeout API?)
  • GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc.
  • Simple and chainable methods for settings and request
  • Request Body can be string, []byte, struct, map, slice and io.Reader too
    • Auto detects Content-Type
    • Buffer less processing for io.Reader
  • Response object gives you more possibility
    • Response Body can be read multiple times
  • Automatic marshal and unmarshal for JSON and XML content type

Examples

Simple GET into a string

var s string
var code int
err := requests.New().
	ToString(&s).
	ToStatusCode(&code).
	Get("https://example.com/get")

POST a raw body with context

err := requests.New().
	Context(ctx).
	Body([]byte(`hello, world`)).    // body type: string/bytes/io.Reader/struct deduced by generics
	Post("https://example.com/post")

HTTP body type can be deduced by generics:

  • bytes -> bytes
  • string -> bytes
  • io.Reader -> ReadAll bytes
  • ...

POST a form body with context, header, param

err := requests.New().
	Context(ctx).
	HeaderPairs("martini", "shaken"). // KV pairs
	ParamPairs("a", "1", "b", "2").  // KV pairs
	FormPairs("name", "apple"). // KV pairs
	Post("https://postman-echo.com/post")

POST a form body with context, header, param - advanced

err := requests.New().
	Context(ctx).
	Headers(map[string]string{"martini": "shaken"}).
	Params(map[string]string{"a": "1", "b": "2"}).
	Form(map[string]string{"name": "apple"}).
	Post("https://postman-echo.com/post")

POST a JSON object and parse the response

var res placeholder
req := placeholder{
	Title:  "foo",
	Body:   "baz",
	UserID: 1,
}
err := requests.New().
	JSON(&req).
	ToJSON(&res).
	Post("https://jsonplaceholder.typicode.com/posts")

Upload one or multiple file(s)

err := requests.New().
	FilePairs("file1", "test1.txt", "file2", "test2.txt"). // field name -> file name pairs
	Post("https://example.com/upload")

Download a file

err := requests.New().
	ToFile("test.txt").
	Get("https://example.com/download")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions