nic

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2019 License: MPL-2.0 Imports: 18 Imported by: 9

README

Nic

GitHub release GitHub issues

English | 中文

Nic is a HTTP request client which has elegant, easy-to-use API


Features

  • wrapper of HTTP std lib, provids elegant and easy-to-use API

  • keep session via nic.Session structure, nic.Session is go-routine safe


Installation

To install nic, enter the following command

$ go get -v -u github.com/eddieivan01/nic

Quick start

Do a HTTP request like this

resp, err := nic.Get("http://example.com", nil)
if err != nil {
    log.Fatal(err.Error())
}
fmt.Println(resp.Text)

Documentation

do a basic request

nic could do these methods' request

"HEAD", "GET", "POST", "DELETE", "OPTIONS", "PUT", "PATCH"

import (
	"fmt"
    "github.com/eddieivan01/nic"
)

func main() {
    url := "http://example.com"
    resp, err := nic.Get(url, nil)
    if err != nil {
        log.Fatal(err.Error())
    }
    fmt.Println(resp.Text)
}

post request with some form data

as you see, all requests' parameters are passed by nic.H, and the inner is saved in nic.KV, it's actually map[string]interface{}

resp, err := nic.Post(url, nic.H{
    Data : nic.KV{
        "nic" : "nic",
    },
    Headers : nic.KV{
        "X-Forwarded-For" : "127.0.0.1",
    },
})

request with cookies

of course, you can also set it in Headers

resp, err := nic.Get(url, nic.H{
    Cookies : nic.KV{
        "cookie" : "nic",
    },
})

request with files

you can upload files with files' name + files' content which is []byte type, and can also upload via local file path

while uploading a file, you can set multipart form's field name, filename and MIME type

for more convenient setting files parameters, you can invoke in a chain to set filename and MIME type

resp, err := nic.Post(url, nic.H{
    Files : nic.KV{
        "file1": nic.File(
                    "nic.go", 
                    []byte("package nic")),
        "file2": nic.FileFromPath("./nic.go").
                    MIME("text/plain").
                    FName("nic"),
    },
})

request with JSON

resp, err := nic.Post(url, nic.H{
    JSON : nic.KV{
        "nic" : "nic",
    }
})

request with unencoded raw message

resp, err := nic.Post(url, nic.H{
    Raw : "post body which is unencoded",
})

using chunked transfer

The default is not to use chunked transfer

enable the transfer-encoding: chunked

resp, _ := nic.Get(url, nic.H{
    Chunked: true,
})

set query params

resp, err := nic.Get(url, nic.H {
    Params: nic.KV {
        "a": "1",
    },
})

all the parameters you could set

H struct {
    Params  KV
    Data    KV
    Raw     string
    Headers KV
    Cookies KV
    Auth    KV
    Proxy   string
    JSON    KV
    Files   KV

    AllowRedirect      bool
    Timeout            int64
    Chunked            bool
    DisableKeepAlives  bool
    DisableCompression bool
    SkipVerifyTLS      bool
}

NOTICE

nic.H can only have one of the following four parameters

H.Raw, H.Data, H.Files, H.JSON

session := nic.NewSession()
resp, err := session.Post("http://example.com/login", nic.H{
    Data : nic.KV{
        "uname" : "nic",
        "passwd" : "nic",
    },
})

// ......

resp, err = session.Get("http://example.com/userinfo", nil)

handle response

resp, _ := nic.Get(url, nil)
fmt.Println(resp.Text)
fmt.Println(resp.Bytes)

handle JSON response

resp, _ := nic.Get(url, nil)

type S struct {
    P1 string `json:"p1"`
    P2 string `json:"p2"`
}

s := &S{}
err := resp.JSON(&s)

if err == nil {
    fmt.Println(s.P1, s.P2)
}

change response's encoding

SetEncode will convert resp.Bytes to resp.Text if encoding is changed every time be called

resp, _ := nic.Get(url, nil)
err := resp.SetEncode("gbk")

if err == nil {
    fmt.Println(resp.Text)
}

save response's content as a file

resp, _ := nic.Get("http://example.com/1.jpg", nil)
err := resp.SaveFile("1.jpg")

register a request/response hook

session := nic.NewSession()
session.RegisterBeforeReqHook(func(r *http.Request) error {
    r.URL.RawQuery = "nic=nic"
    return nil
})
session.RegisterAfterRespHook(func(r *http.Response) error {
    r.Header.Set("nic", "nic")
    return nil
})

session.Get(url, nil)

QA

  • Q:

    How to get origin *http.Request from nic.Session?

    A:

    by nic.Session.GetRequest method

  • Q:

    How to pass origin *http.Response to goquery-like DOM-parsing-libs from nic.Response?

    A:

    use resp, _ := nic.Get(...); resp.Response to access origin anonymous structure *http.Response; and (*http.Response).Body's IO.Reader has been saved, you can use *http.Response as if it were the original structure

  • Q:

    Redirection is allowed 10 times by default, how could I increase the number?

    A:

    by access nic.Session.Client then change its CheckRedirect property

  • Q:

    How to use the chunked transfer-encoding?

    A:

    by nic.H{Chunked: true}

Documentation

Index

Constants

View Source
const (
	HEAD    = "HEAD"
	GET     = "GET"
	POST    = "POST"
	DELETE  = "DELETE"
	OPTIONS = "OPTIONS"
	PUT     = "PUT"
	PATCH   = "PATCH"
)

Variables

View Source
var (
	// ErrInvalidMethod will be throwed when method not in
	// [HEAD, GET, POST, DELETE, OPTIONS, PUT, PATCH, CONNECT, TRACE]
	ErrInvalidMethod = errors.New("nic: Method is invalid")

	// ErrFileInfo will be throwed when fileinfo is invalid
	ErrFileInfo = errors.New("nic: Invalid file information")

	// ErrParamConflict will be throwed when options params conflict
	// e.g. files + data
	//      json + data
	//      ...
	ErrParamConflict = errors.New("nic: Options param conflict")

	// ErrUnrecognizedEncoding will be throwed while changing response encoding
	// if encoding is not recognized
	ErrUnrecognizedEncoding = errors.New("nic: Unrecognized encoding")

	// ErrNotJsonResponse will be throwed when response not a json
	// but invoke Json() method
	ErrNotJsonResponse = errors.New("nic: Not a Json response")

	// ErrHookFuncMaxLimit will be throwed when the number of hook functions
	// more than MaxLimit = 8
	ErrHookFuncMaxLimit = errors.New("nic: The number of hook functions must be less than 8")

	// ErrIndexOutofBound means the index out of bound
	ErrIndexOutofBound = errors.New("nic: Index out of bound")
)

Functions

This section is empty.

Types

type AfterResponseHookFunc added in v0.3.1

type AfterResponseHookFunc func(*http.Response) error

type BeforeRequestHookFunc added in v0.3.1

type BeforeRequestHookFunc func(*http.Request) error

type F

type F struct {
	Src      []byte
	FilePath string
	FileName string
	MimeType string
}

when upload a file, we use nic.KV again nic.File returns F struct

nic.KV {
    "file1" :"file" : nic.FileFromPath("test.go"),
    "file2" : nic.File("test.go", []byte("package nic")).
					FName("nic.go").
					MIME("text/plain"),
    "token" : "abc",
}

the POST body is:

Content-Type: multipart/form-data; boundary=e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf

--e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf Content-Disposition: form-data; name="file1"; filename="test.go" Content-Type: application/octet-stream

package test --e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf Content-Disposition: form-data; name="token"

abc --e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf Content-Disposition: form-data; name="file2"; filename="nic.go" Content-Type: text/plain

package test --e7d105eae032bdc774a787f1d874269d04499cb284477d6d77889be73caf--

F struct saves file form information

func File added in v0.2.1

func File(filename string, src []byte) *F

File returns a new file struct

func FileFromPath added in v0.2.1

func FileFromPath(path string) *F

FileFromPath returns a file struct from file path

func (*F) FName added in v0.2.1

func (f *F) FName(filename string) *F

FName changes file's filename in multipart form invoke it in a chain

func (*F) MIME added in v0.2.1

func (f *F) MIME(mimetype string) *F

MIME changes file's mime type in multipart form invoke it in a chain

type H

type H struct {
	Params  KV
	Data    KV
	Raw     string
	Headers KV
	Cookies KV
	Auth    KV
	Proxy   string
	JSON    KV
	Files   KV

	AllowRedirect      bool
	Timeout            int64
	Chunked            bool
	DisableKeepAlives  bool
	DisableCompression bool
	SkipVerifyTLS      bool
}

H struct is options for request and http client

type KV

type KV map[string]interface{}

KV is used for H struct

type Option added in v0.2.1

type Option interface {
	// contains filtered or unexported methods
}

Option is the interface implemented by `H` and `*H`

type Response

type Response struct {
	*http.Response

	Text  string
	Bytes []byte
	// contains filtered or unexported fields
}

Response is the wrapper for http.Response

func Delete

func Delete(url string, option Option) (*Response, error)

Delete implemented by Session.Delete

func Get

func Get(url string, option Option) (*Response, error)

Get implemented by Session.Get

func Head(url string, option Option) (*Response, error)

Head implemented by Session.Head

func NewResponse added in v0.2.1

func NewResponse(r *http.Response) (*Response, error)

func Options

func Options(url string, option Option) (*Response, error)

Options implemented by Session.Options

func Patch

func Patch(url string, option Option) (*Response, error)

Patch implemented by Session.Patch

func Post

func Post(url string, option Option) (*Response, error)

Post implemented by Session.Post

func Put

func Put(url string, option Option) (*Response, error)

Put implemented by Session.Put

func (Response) GetEncode

func (r Response) GetEncode() string

GetEncode returns Response.encoding

func (Response) JSON

func (r Response) JSON(s interface{}) error

JSON could parse http json response

func (Response) SaveFile added in v0.2.1

func (r Response) SaveFile(filename string) error

SaveFile save bytes data to a local file

func (*Response) SetEncode

func (r *Response) SetEncode(e string) error

SetEncode changes Response.encoding and it changes Response.Text every times be invoked

type Session

type Session struct {
	Client *http.Client

	sync.Mutex
	// contains filtered or unexported fields
}

Session is the wrapper for http.Client and http.Request

func NewSession added in v0.2.1

func NewSession() *Session

NewSession returns an empty Session

func (*Session) Delete

func (s *Session) Delete(url string, option Option) (*Response, error)

Delete is a shortcut for get method

func (*Session) Get

func (s *Session) Get(url string, option Option) (*Response, error)

Get is a shortcut for get method

func (*Session) GetRequest added in v0.1.1

func (s *Session) GetRequest() *http.Request

GetRequest returns nic.Session.request

func (*Session) Head

func (s *Session) Head(url string, option Option) (*Response, error)

Head is a shortcut for get method

func (*Session) Options

func (s *Session) Options(url string, option Option) (*Response, error)

Options is a shortcut for get method

func (*Session) Patch

func (s *Session) Patch(url string, option Option) (*Response, error)

Patch is a shortcut for get method

func (*Session) Post

func (s *Session) Post(url string, option Option) (*Response, error)

Post is a shortcut for get method

func (*Session) Put

func (s *Session) Put(url string, option Option) (*Response, error)

Put is a shortcut for get method

func (*Session) RegisterAfterRespHook added in v0.3.1

func (s *Session) RegisterAfterRespHook(fn AfterResponseHookFunc) error

Register the after response hook

func (*Session) RegisterBeforeReqHook added in v0.3.1

func (s *Session) RegisterBeforeReqHook(fn BeforeRequestHookFunc) error

Register the before request hook

func (*Session) Request

func (s *Session) Request(method string, urlStr string, option Option) (*Response, error)

Request is the base method

func (*Session) ResetAfterRespHook added in v0.3.1

func (s *Session) ResetAfterRespHook()

Reset all after response hook

func (*Session) ResetBeforeReqHook added in v0.3.1

func (s *Session) ResetBeforeReqHook()

Reset all before request hook

func (*Session) UnregisterAfterRespHook added in v0.3.1

func (s *Session) UnregisterAfterRespHook(index int) error

Unregister the response hook, pass the function's index(start at 0)

func (*Session) UnregisterBeforeReqHook added in v0.3.1

func (s *Session) UnregisterBeforeReqHook(index int) error

Unregister the request hook, pass the function's index(start at 0)

Jump to

Keyboard shortcuts

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