xreq

package module
v0.0.0-...-de28aae Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2021 License: MIT Imports: 11 Imported by: 0

README

xReq

Go Report Card Sourcegraph

xReq is a easy-to-use, flexiable and extendable Go HTTP Client.

Quick Start

package main

import (
	"fmt"

	"github.com/ehyyoj/xreq"
)

func main() {
	data, code, err := xreq.GetBytes("http://localhost:8080/hello",
            xreq.WithQueryValue("name", "jack"),
            xreq.WithSetHeader("x-request-id", "123"),
	)
	if err != nil {
		panic(err)
	}
	fmt.Printf("response body: %s, status code: %d", string(data), code)
}

Post a JSON request

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/ehyyoj/xreq"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	user := &User{
		Name: "jack",
		Age:  18,
	}

	// use context.Context to set request timeout.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
	defer cancel()
	data, code, err := xreq.DoBytes("http://localhost:8080/hello",
		xreq.WithPostJSON(user),
		xreq.WithContext(ctx), 
	)
	fmt.Println("response:", string(data), code, err)
}

Send Post form with header

package main

import (
	"fmt"
	"time"

	"github.com/ehyyoj/xreq"
)

func main() {
	client := xreq.NewClient(xreq.Config{
		Timeout: time.Second * 2,
	}, xreq.WithCheckStatus(true))
	params := make(map[string]string)
	params["name"] = "jack"
	params["age"] = "18"
	data, code, err := client.DoBytes("http://localhost:8080/hello",
		xreq.WithPostForm(params),
		xreq.WithSetHeader("x-request-id", "123"),
		xreq.WithQueryValue("pageIndex", "2"),
		xreq.WithQueryValue("pageSize", "10"),
	)
	fmt.Println("response:", string(data), code, err)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

func Do(url string, opt ...Option) (*http.Response, error)

Do method construct a HTTP request with options Example:

resp, err := Do("http://localhost/api",

WithPostJSON(v),
WithCheckStatus(true))

and return the *http.Response.

func DoBytes

func DoBytes(url string, opt ...Option) (data []byte, code int, err error)

DoBytes method construct a HTTP request with options and return the bytes of resp.Body and http.StatusCode

func Get

func Get(url string, opt ...Option) (*http.Response, error)

Get issues a GET with options to the specified URL and return *http.Response.

func GetBytes

func GetBytes(url string, opt ...Option) (data []byte, code int, err error)

GetBytes issues GET with options to the specified URL and return the bytes of the resp.Body.

func Post

func Post(url, contentType string, body io.Reader, opt ...Option) (*http.Response, error)

Post issues a POST with options to the specified URL and return *http.Response. This method is compatible with the original usage please use Do or DoBytes as much as possible.

func PostBytes

func PostBytes(url, contentType string, body io.Reader, opt ...Option) (data []byte, code int, err error)

PostBytes issues a POST with options to the specified URL and return the bytes of the resp.Body. This method is compatible with the original usage please use Do or DoBytes as much as possible.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps a HTTP Client that support functional options and make HTTP requests easier. It also compatible with the http.Client.

func NewClient

func NewClient(conf Config, opt ...Option) *Client

NewClient return a Client instance.

func (*Client) Do

func (c *Client) Do(url string, opt ...Option) (*http.Response, error)

Do method construct a HTTP request with options Example:

resp, err := Do("http://localhost/api",

WithPostJSON(v),
WithCheckStatus(true))

and return the *http.Response.

func (*Client) DoBytes

func (c *Client) DoBytes(url string, opt ...Option) (data []byte, code int, err error)

DoBytes method construct a HTTP request with options and return the bytes of resp.Body and http.StatusCode.

func (*Client) Get

func (c *Client) Get(url string, opt ...Option) (*http.Response, error)

Get issues a GET with options to the specified URL and return *http.Response.

func (*Client) GetBytes

func (c *Client) GetBytes(url string, opt ...Option) (data []byte, code int, err error)

GetBytes issues GET with options to the specified URL and return the bytes of the resp.Body.

func (*Client) Post

func (c *Client) Post(url, contentType string, body io.Reader, opt ...Option) (*http.Response, error)

Post issues a POST with options to the specified URL and return *http.Response. This method is compatible with the original usage please use Do or DoBytes as much as possible.

func (*Client) PostBytes

func (c *Client) PostBytes(url, contentType string, body io.Reader, opt ...Option) (data []byte, code int, err error)

PostBytes issues a POST with options to the specified URL and return the bytes of the resp.Body. This method is compatible with the original usage please use Do or DoBytes more likely.

type Config

type Config struct {
	Timeout   time.Duration
	Transport http.RoundTripper
}

Config defines a config for Client.

type Option

type Option func(o *Options)

Option is a type define use for pass closure as parameters.

func WithAddCookie

func WithAddCookie(cookie *http.Cookie) Option

WithAddCookie set http.Cookie.

func WithBodyBytes

func WithBodyBytes(contentType string, data []byte) Option

WithBodyBytes set []byte into the request body.

func WithBodyReader

func WithBodyReader(contentType string, body io.Reader) Option

WithBodyReader set io.Reader into the request body.

func WithBodyString

func WithBodyString(contentType string, body string) Option

WithBodyString set string into the request body.

func WithCheckStatus

func WithCheckStatus(check bool) Option

WithCheckStatus treat non-200 as error NOTE it only effected which method with bytes return, method with *http.Response return does not effected.

func WithContext

func WithContext(ctx context.Context) Option

WithContext set context to the http.Request it use to timeout or cancel.

Example:

ctx, cancel := context.WithCancel(context.Background(), time.Second*3) defer cancel() data, _, err := xreq.GetBytes(url,

WithContext(ctx),

)

func WithHeader

func WithHeader(header http.Header) Option

WithHeader set up the entire http.Header.

func WithMethod

func WithMethod(method string) Option

WithMethod set the http method.

func WithMultipart

func WithMultipart(params map[string]string) Option

WithMultipart set the multipart/form-data without file.

func WithMultipartFile

func WithMultipartFile(fieldname, filename string, data []byte, params ...map[string]string) Option

WithWithMultipartFile use multipart/form-data format to upload file.

func WithPostForm

func WithPostForm(params map[string]string) Option

WithPostForm set the entire post form

func WithPostJSON

func WithPostJSON(v interface{}) Option

WithPostJSON marshal v to the JSON bytes and set to the request body.

func WithQuery

func WithQuery(params map[string]string) Option

WithQuery set the URL query

func WithQueryValue

func WithQueryValue(key, value string) Option

WithQueryValue set key-value into query. Example:

body, err := Get("http://localhost/api",

WithQuery("name", "jack"),
WithQuery("id", "18"))

and the request URL will be "http://localhost/api?name=jack&id=18"

func WithRequest

func WithRequest(req *http.Request) Option

WithRequest replace the http.Request entirely.

func WithSetHeader

func WithSetHeader(k, v string) Option

WithSetHeader set key-value into http.Header.

type Options

type Options struct {
	*http.Request

	Err    error
	Values urlpkg.Values
	// contains filtered or unexported fields
}

Options define some option of HTTP.

Jump to

Keyboard shortcuts

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