Skip to content

Latest commit

 

History

History
94 lines (67 loc) · 2.21 KB

README.md

File metadata and controls

94 lines (67 loc) · 2.21 KB

About

Go Go Report Card LICENSE

giant-stone/go is a Go library which provides utility functions for common programming tasks. Confirm to https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

Life is short, don't repeat yourself.

Modules

ghttp - HTTP client wrapper in Method chaining.
ghttpcache - caching ghttp response in process memory or Redis.
gsql - SQL CRUD and search wrapper.

Examples

Send a HTTP GET request in ghttp

Custom HTTP request timeout, method, proxy and body in Method chaining

package main


import (
	"log"
	"os"
	"time"

	"github.com/giant-stone/go/ghttp"
)

func main() {
	fullurl := "https://httpbin.org/post"
	postData := []byte(`{"msg":"hello"}`)
	req := ghttp.New().
		SetRandomUserAgent(true).
		SetTimeout(time.Second * 3).
		SetRequestMethod("POST").
		SetUri(fullurl).
		SetProxy(os.Getenv("HTTPS_PROXY")).
		SetPostBody(&postData)
	err := req.Send()
	if ghttp.CheckRequestErr(fullurl, req.RespStatus, req.RespBody, err) {
		log.Println("handler error ...")
	}

	log.Println("process response body ...", len(req.RespBody))
}

Send a POST multipart/form-data request in ghttp

	var err error

	rq := ghttp.New().
		SetDebug(true).
		SetRequestMethod("POST").
		SetUri("https://httpbin.org/post").
		SetTimeout(time.Second * 5)

	var b bytes.Buffer
	w := multipart.NewWriter(&b)

	err = ghttp.AppendMultipartFormData(w, "myfile", "myfile.data", []byte(`hello 中文`))
	gutil.ExitOnErr(err)

	err = ghttp.AppendMultipartFormData(w, "myfile2", "myfile2.data", []byte(`foo\nbar`))
	gutil.ExitOnErr(err)

	err = w.WriteField("id", "123")
	gutil.ExitOnErr(err)

	err = w.Close()
	gutil.ExitOnErr(err)

	rqBody := b.Bytes()

	rq.SetPostBody(&rqBody)
	rq.SetHeader("Content-Type", w.FormDataContentType())
	err = rq.Send()
	gutil.ExitOnErr(err)

	log.Println(
		rq.RespStatus,
		string(rq.RespBody),
	)