nic

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 19, 2019 License: MPL-2.0 Imports: 14 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

  • thread(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", "CONNECT", "TRACE"

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 data
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
resp, err := nic.Get(url, &nic.H{
    Cookies : nic.KV{
        "cookie1" : "nic",
    },
})
request with files
resp, err := nic.Post(url, &nic.H{
    Files : nic.F{
        "file" : nic.KV{
            // path of file, filename will be `nic.go`
            "filename" : `/home/nic/nic.go`,
            "token" : "0xff",
        },
    },
})
request with JSON
resp, err := nic.Post(url, &nic.H{
    JSON : nic.KV{
        "nic" : "nic",
    }
})
request with unencoded message
resp, err := nic.Post(url, &nic.H{
    Raw : "post body which is unencoded",
})
all the parameters
H struct {
    AllowRedirect bool
    Timeout       int64
    Data          KV
    Raw           string
    Headers       KV
    Cookies       KV
    Auth          KV
    Proxy         string

    JSON  KV
    Files F
}
NOTICE!!!

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

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

session := &nic.Session{}
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, _ := nil.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, _ := nil.Get(url, nil)
err := resp.SetEncode("gbk")

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

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

Documentation

Index

Constants

This section is empty.

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")
)

Functions

This section is empty.

Types

type F

type F map[string]KV

F is for file-upload request

map[string]KV{
    "file1" : KV{
                 // path of file
                 "filename" : "1.txt",
                 "token" : "abc",
              },
    "file2" : KV{...},
}

type H

type H struct {
	AllowRedirect bool
	Timeout       int64
	Data          KV
	Raw           string
	Headers       KV
	Cookies       KV
	Auth          KV
	Proxy         string

	JSON  KV
	Files F
}

H struct is options for request and http client

type KV

type KV map[string]string

KV is used for H struct

type Response

type Response struct {
	*http.Response

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

Response is the wrapper for http.Response

func Connect

func Connect(url string, options *H) (*Response, error)

Connect implemented by Session.Connect

func Delete

func Delete(url string, options *H) (*Response, error)

Delete implemented by Session.Delete

func Get

func Get(url string, options *H) (*Response, error)

Get implemented by Session.Get

func Head(url string, options *H) (*Response, error)

Head implemented by Session.Head

func Options

func Options(url string, options *H) (*Response, error)

Options implemented by Session.Options

func Patch

func Patch(url string, options *H) (*Response, error)

Patch implemented by Session.Patch

func Post

func Post(url string, options *H) (*Response, error)

Post implemented by Session.Post

func Put

func Put(url string, options *H) (*Response, error)

Put implemented by Session.Put

func Trace

func Trace(url string, options *H) (*Response, error)

Trace implemented by Session.Trace

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 if is not a json response, returns ErrNotJsonResponse

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

	Cookies []*http.Cookie
	// contains filtered or unexported fields
}

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

func (*Session) ClearCookies

func (s *Session) ClearCookies()

ClearCookies deletes all cookies

func (*Session) Connect

func (s *Session) Connect(url string, options *H) (*Response, error)

Connect is a shortcut for get method

func (*Session) Delete

func (s *Session) Delete(url string, options *H) (*Response, error)

Delete is a shortcut for get method

func (*Session) Get

func (s *Session) Get(url string, options *H) (*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, options *H) (*Response, error)

Head is a shortcut for get method

func (*Session) Options

func (s *Session) Options(url string, options *H) (*Response, error)

Options is a shortcut for get method

func (*Session) Patch

func (s *Session) Patch(url string, options *H) (*Response, error)

Patch is a shortcut for get method

func (*Session) Post

func (s *Session) Post(url string, options *H) (*Response, error)

Post is a shortcut for get method

func (*Session) Put

func (s *Session) Put(url string, options *H) (*Response, error)

Put is a shortcut for get method

func (*Session) Request

func (s *Session) Request(method string, urlStr string, options *H) (*Response, error)

Request is the base method

func (*Session) Trace

func (s *Session) Trace(url string, options *H) (*Response, error)

Trace is a shortcut for get method

Jump to

Keyboard shortcuts

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