httpclient

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2021 License: MIT Imports: 11 Imported by: 0

README

a wraper of http package to send request

surport chainable usage

Examples

package main

import (
	hc "gitee.com/rdor/httpclient"
	
	"net/http"
)

func main() {
	person := struct {
		Age  int
		Name string
	}{Age: 27, Name: "Tom"}

	hc.New().
		Post("http://127.0.0.1:8888/test").
		Header("some key", "some value").
		ContentType(hc.ContentTypeJson).
		Body(person).
		Do(func(response *http.Response, body []byte, err error) {
		// do something with response
	})
}

or

client := hc.New().
    Post("http://127.0.0.1:8888/test").
    Header("some key", "some value").
    ContentType(hc.ContentTypeJson).
    Body(person)
resp, body, err := client.Go()
...

you can review at test cases to see more exapmples

Documentation

Overview

Example
var persons []Person
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	defer func() {
		_ = r.Body.Close()
	}()
	body, _ := ioutil.ReadAll(r.Body)

	switch r.Method {
	case GET:
		if data, err := json.Marshal(persons); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			_, _ = w.Write(nil)
		} else {
			w.WriteHeader(http.StatusOK)
			_, _ = w.Write(data)
		}
	case PUT:
		var p Person
		err := json.Unmarshal(body, &p)
		if err != nil {
			w.WriteHeader(http.StatusNotAcceptable)
			_, _ = w.Write([]byte("body in request is not a person"))
			return
		}
		persons = append(persons, p)
		w.WriteHeader(http.StatusOK)
	case POST:
		var p Person
		err := json.Unmarshal(body, &p)
		if err != nil {
			w.WriteHeader(http.StatusNotAcceptable)
			_, _ = w.Write([]byte("body in request is not a person"))
			return
		}
		indexToReplace := -1
		for index, pp := range persons {
			if pp.Name == p.Name {
				indexToReplace = index
				break
			}
		}
		if indexToReplace > -1 {
			persons[indexToReplace] = p
			w.WriteHeader(http.StatusOK)
			return
		}
		w.WriteHeader(http.StatusNotFound)
		_, _ = w.Write([]byte("the person not found"))
	case DELETE:
		var p Person
		err := json.Unmarshal(body, &p)
		if err != nil {
			w.WriteHeader(http.StatusNotAcceptable)
			_, _ = w.Write([]byte("body in request is not a person"))
			return
		}
		var newPersons []Person
		for _, pp := range persons {
			if pp.Name != p.Name {
				newPersons = append(newPersons, pp)
			}
		}
		if len(persons)-1 == len(newPersons) {
			persons = newPersons
			w.WriteHeader(http.StatusOK)
		} else {
			w.WriteHeader(http.StatusNotFound)
			_, _ = w.Write([]byte("the person not found"))
			return
		}
	}
}))
defer server.Close()

dog := Pet{Name: "wangwang", Color: "black"}
tom := Person{Name: "Tom", Age: 27, Pet: dog}

cat := Pet{Name: "miumu", Color: "white"}
joe := Person{Name: "Joe", Age: 3, Pet: cat}

addPerson(server.URL+"/add", tom)
addPerson(server.URL+"/add", joe)
queryPersons(server.URL + "/persons")
modifyPersonAge(server.URL+"/modify", joe, 5)
removePerson(server.URL+"/remove", tom)
queryPersons(server.URL + "/persons")
Output:

quiried persons: [{27 Tom {wangwang black}} {3 Joe {miumu white}}]
quiried persons: [{5 Joe {miumu white}}]

Index

Examples

Constants

View Source
const (
	// HTTP methods we support
	POST    = "POST"
	GET     = "GET"
	HEAD    = "HEAD"
	PUT     = "PUT"
	DELETE  = "DELETE"
	PATCH   = "PATCH"
	OPTIONS = "OPTIONS"

	HeaderContentType   = "Content-Type"
	ContentTypeJson     = "application/json"
	ContentTypeJsonUTF8 = "application/json;charset=UTF-8"
	ContentTypeForm     = "application/x-www-form-urlencoded"
	ContentTypeText     = "text/plain"
	ContentTypeXml      = "application/xml"

	DefaultTimeout               = 60 * time.Second
	DefaultDialTimeout           = 30 * time.Second
	DefaultKeepAliveTimeout      = 30 * time.Second
	DefaultIdleConnTimeout       = 90 * time.Second
	DefaultTLSHandshakeTimeout   = 10 * time.Second
	DefaultExpectContinueTimeout = 1 * time.Second
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CallBack

type CallBack func(response *http.Response, body []byte, err error)

type CallBackStr

type CallBackStr func(response *http.Response, body string, err error)

type Client

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

func New

func New() *Client

func (*Client) AddCACert

func (c *Client) AddCACert(cert *x509.Certificate) *Client

func (*Client) AddCAContent

func (c *Client) AddCAContent(cacontent []byte) *Client

func (*Client) AddCAFile

func (c *Client) AddCAFile(cafile string) *Client

func (*Client) AddCert

func (c *Client) AddCert(cert tls.Certificate) *Client

func (*Client) AddCertContent

func (c *Client) AddCertContent(certContent, keyContent []byte) *Client

func (*Client) AddCertFile

func (c *Client) AddCertFile(cert, key string) *Client

func (*Client) AppendQueries added in v1.1.0

func (c *Client) AppendQueries(queries map[string]string) *Client

func (*Client) AppendQuery added in v1.1.0

func (c *Client) AppendQuery(key, value string) *Client

func (*Client) Body

func (c *Client) Body(body interface{}) *Client

body can be defined struct, string, map, array(or slice), and so on

func (*Client) CertPool

func (c *Client) CertPool(pool *x509.CertPool) *Client

func (*Client) ContentType

func (c *Client) ContentType(contentType string) *Client

func (*Client) DebugString

func (c *Client) DebugString() string

func (*Client) Delete

func (c *Client) Delete(url string) *Client

func (*Client) DialTimeout

func (c *Client) DialTimeout(timeout time.Duration) *Client

func (*Client) Do

func (c *Client) Do(callback CallBack)

func (*Client) DoStr

func (c *Client) DoStr(callback CallBackStr)

func (*Client) ExpectContinueTimeout

func (c *Client) ExpectContinueTimeout(timeout time.Duration) *Client

func (*Client) Get

func (c *Client) Get(url string) *Client

func (*Client) Go

func (c *Client) Go() (*http.Response, []byte, error)

func (*Client) GoStr

func (c *Client) GoStr() (*http.Response, string, error)

func (*Client) Head

func (c *Client) Head(url string) *Client

func (*Client) Header

func (c *Client) Header(k, v string) *Client

func (*Client) IdleConnTimeout

func (c *Client) IdleConnTimeout(timeout time.Duration) *Client

func (*Client) InsecureSkipVerify

func (c *Client) InsecureSkipVerify(skip bool) *Client

func (*Client) KeepAliveTimeout

func (c *Client) KeepAliveTimeout(timeout time.Duration) *Client

func (*Client) Options

func (c *Client) Options(url string) *Client

func (*Client) Patch

func (c *Client) Patch(url string) *Client

func (*Client) Post

func (c *Client) Post(url string) *Client

func (*Client) Put

func (c *Client) Put(url string) *Client

func (*Client) ReNew

func (c *Client) ReNew(method, url string) *Client

func (*Client) TLSHandshakeTimeout

func (c *Client) TLSHandshakeTimeout(timeout time.Duration) *Client

func (*Client) Timeout

func (c *Client) Timeout(timeout time.Duration) *Client

func (*Client) TlsConfig

func (c *Client) TlsConfig(config *tls.Config) *Client

Jump to

Keyboard shortcuts

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