goreq

package module
v1.0.3-alpha Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2018 License: Apache-2.0 Imports: 10 Imported by: 1

README

goreq

Build Status GoDoc LICENSE

A simple http request library for golang.

Install

go get github.com/xioxu/goreq

Simple to use

    req := goreq.Req(nil)
	body,_,_ := req.Get("https://www.baidu.com").Do()
	fmt.Print(string(body))

Table of contents

Options

Property Description Notes
Method HTTP method -
URL Fully qualified uri -
Proxy Address of an HTTP proxy -
Headers HTTP headers to setup for the request -
FollowRedirect Follow HTTP 3xx responses as redirects default: true , you can use goreq.TrueVal or goreq.FalseVal to set
DisableKeepAlive Disable keep alive feature default: false, you can use goreq.TrueVal or goreq.FalseVal to set
Jar A cookie Jar to use for multiple subsequent requests You can define your own custom cookie jar; see cookies section in following
QueryString Object containing querystring values to be appended to the uri -
Timeout Request timeout value Global request timeout(e.g: 15 * time.Second), see https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/#clienttimeouts
HeadersToBeRemove The headers you want to remove before send request -

Proxy

If you specify a proxy option, then the request (and any subsequent redirects) will be sent via a connection to the proxy server.

    req := goreq.Req(&goreq.ReqOptions{ Proxy: goreq.NewString("http://localhost:8888")})
	body,resp,_ := req.Get("https://www.baidu.com").Do()
	fmt.Println(string(body))
	fmt.Println(resp.StatusCode)

Pipe

There are some Pipe methods to handle different case:

PipeStream

You can pipe any response to a writer. (Refer to UT: TestPipeSream)

  req := goreq.Req(nil)
  req.Get("https://www.baidu.com").PipeStream(fileStream)
PipeReq

You can pipe a request result to next request (Refer to UT: TestPipeReq)

  req1 := goreq.Req(nil)
  req2 := goreq.Req(nil)
  req2.Post("http://www.bbb.com/submit")
  req.Get("https://www.baidu.com").PipeReq(req2)
PipeFromReq

Pipe the http.Request content to goReq request (UT: TestPipeFromReq)

PipeToResponse

Pipe the result to a http.Response

We can create a reverseProxy server through PipeFromReq and PipeToResponse easily:

if err := http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		req := goreq.Req(&goreq.ReqOptions{
			Method: r.Method,
			Url:    "https://www.baidu.com" + r.RequestURI,
		})

		req.PipeFromReq(r).PipeToResponse(w)
	})); err != nil {
		panic(err)
	}

BodyContent

You can set the request body with the folloing methods:

  • JsonObject
  • JsonString
  • FormData
	req := Req(nil)

	v := url.Values{
		"username": []string{"test"},
		"password": []string{"test"},
	}

	body,_, err := req.Post("http://localhost/login").FormData(v).Do()

	if err != nil{
		fmt.Print(body)
	}
cookieJar,_ := cookiejar.New(nil)
req := goreq.Req(&goreq.ReqOptions{
			Method: "get",
			Url:    "https://www.baidu.com",
			Jar:cookieJar,
		})

Documentation

Overview

Package goreq provides the ability to do http request with the simplest code

Example to Request a site

    req := goreq.Req(nil)
	body,_,_ := req.Get("https://www.baidu.com").Do()
	fmt.Print(string(body))

Example to submit a request

req := goreq.Req(nil)
postFormData := url.Values{}
postFormData.Add("userName", "nxu")
postFormData.Add("pwd", "111")

body,_,_ := req.Post("https://www.baidu.com").FormData(postFormData).Do()
fmt.Print(string(body))

This top-level package contains utility functions and data types that are used throughout the http requesting.

Index

Examples

Constants

This section is empty.

Variables

View Source
var FalseVal = &falseVal
View Source
var TrueVal = &trueVal

Functions

func NewString

func NewString(str string) *string

Types

type GoReq

type GoReq struct {
	Options *ReqOptions
	// contains filtered or unexported fields
}

GoReq stores details that are required to interact with a http request and represents the methods to manipulates the request data.

Generally, you acquire a GoRep by calling goReq.Req() method.

GoReq is not thread safe, so do not use it in concurrency case, but you can reuse it to do different http request, and it is also the suggested usage

func Req

func Req(options *ReqOptions) *GoReq

Req prepares a GoReq instance. A basic example of using this would be:

req := goreq.Req(nil)
Example
req := Req(nil)
body, _, _ := req.Get("https://www.baidu.com").Do()
fmt.Print(string(body))
Output:

func (*GoReq) Do

func (req *GoReq) Do() ([]byte, *http.Response, error)

Do method sends the request and return the result

func (*GoReq) FormData

func (req *GoReq) FormData(formData url.Values) *GoReq

FormData sets the http request body and makes the content-type to "application/x-www-form-urlencoded"

func (*GoReq) Get

func (req *GoReq) Get(url string) *GoReq

Get indicates use get method and the get url, equals to:

req.Options.Url = url
req.Options.Method = "GET"

func (*GoReq) JsonObject

func (req *GoReq) JsonObject(jsonObj interface{}) *GoReq

JsonObject sets the http request body and makes the content-type to "application/json"

func (*GoReq) JsonString

func (req *GoReq) JsonString(jsonStr []byte) *GoReq

JsonString sets the http request body and makes the content-type to "application/json"

func (*GoReq) PipeFromHttpReq

func (req *GoReq) PipeFromHttpReq(r *http.Request) *GoReq

PipeFromHttpReq pips the http.Request content to goReq request

func (*GoReq) PipeReq

func (req *GoReq) PipeReq(nextReq *GoReq) (*GoReq, error)

PipeReq pipes the request result to next request

Example
if err := http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

	req := Req(&ReqOptions{
		Method: r.Method,
		Url:    "https://www.baidu.com" + r.RequestURI,
	})

	req.PipeFromHttpReq(r).PipeToResponse(w)
})); err != nil {
	panic(err)
}
Output:

func (*GoReq) PipeStream

func (req *GoReq) PipeStream(writer io.Writer) error

PipeStream pipes the response to a writer (e.g: file stream).

func (*GoReq) PipeToResponse

func (req *GoReq) PipeToResponse(w http.ResponseWriter) error

PipeToResponse pipes the result to a http.Response

func (*GoReq) Post

func (req *GoReq) Post(url string) *GoReq

Post indicates use post method and the post url, equals to:

req.Options.Url = url
req.Options.Method = "POST"

func (*GoReq) Req

func (req *GoReq) Req(options *ReqOptions) *GoReq

Req returns a GoRep with a nother GoRep options

Example
req := Req(&ReqOptions{Proxy: NewString("http://localhost:8888")})

// req1 still keeps the options of req
req1 := req.Req(nil)
req1.Get("http://www.baidu.com").Do()
Output:

func (*GoReq) UnmarshalJson

func (req *GoReq) UnmarshalJson(result interface{}) (*http.Response, error)

UnmarshalJson unmarshals json result to a model

type ReqOptions

type ReqOptions struct {
	//http method (default: "GET"), case insensitive
	Method string

	//fully qualified uri or a parsed url object from url.parse()
	Url string

	//http headers (default: {})
	Headers http.Header

	// follow HTTP 3xx responses as redirects (default: true).
	FollowRedirect *bool

	// disable keep alive feature (default: false)
	DisableKeepAlive *bool

	// if not nil, remember cookies for future use (or define your custom cookie jar; see examples section)
	Jar *cookiejar.Jar

	//an HTTP proxy url to be used
	Proxy *string

	// object containing querystring values to be appended to the uri
	QueryString url.Values

	// e.g 15 * time.Second
	Timeout time.Duration

	HeadersToBeRemove []string
	// contains filtered or unexported fields
}

ReqOptions stores information needed during http request

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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