Simple and lightweight golang package for http requests. based on powerful net/http
Grequest is inspired by the Request library for Python and Guzzle in PHP, the goal is to make a simple and convenient library for making http requests in go
The library has a flexible API with methods that return a pointer to the library structure, which allows you to declaratively describe a request using a chain of methods.
Installation
go get github.com/lib4u/grequest
Usage
Simple get request anf get string response
req := app.Get("https://jsonplaceholder.typicode.com/todos/1").Do()
response := req.Body().GetStrings()
fmt.Println(response)
Get a response and writing it to a json structure
type AutoGenerated struct {
UserID int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
...
var myJsonResponse AutoGenerated
req := app.Get("https://jsonplaceholder.typicode.com/todos/1").Do()
err := req.Body().GetWithJsonStruct(&myJsonResponse)
if err != nil {
fmt.Println("do ..")
}
fmt.Println(myJsonResponse.Title)
Simple post request with json payload body and get status of response
data := LoginRequest{
Username: "example",
Password: "12345",
}
req := app.Post("https://example.site/login").Body().SetJson(data).Do()
fmt.Println(req.Status().GetCode())
Simple save file from response
// file will saved as ../files/image.png
app.Get("https://example.com/image.png").Do().Body().SaveFile()
//OR
app.Get("https://example.com/image.png").Do().Body().Path("/user/files").SaveFile()
//OR
app.Get("https://example.com/image.png").Do().Body().ToFile("path/savedimage.png")
Sending form with files and text fields and set header
req := app.Post("https://example.site/form/")
req.Header().Set("Client", "number_1")
form := req.FormData().WithMultipart()
form.AddField("first_name", "John")
form.AddField("last_name", "Doe")
form.AddFile("photo", "my_photo.png")
form.AddFile("documents", "example.txt")
form.AddFile("documents", "example2.txt")
form.Push()
req.Do()
.....
Request with authentication
//With basic auth
req := app.Post("https://example.site/secret)
req.Header().Set("Client", "number_1")
req.Auth().SetBasic("user", "password")
req.Do()
...
//Sets bearer token
req := app.Post("https://example.site/secret)
req.Header().Set("Client", "number_1")
req.Auth().SetBearer("myToken")
req.Do()
Work with cookie
//Save cookie to file
//By default this saved in cookies/example.site/cookies.json
req := app.Post("https://example.site/cookies")
req.Cookie().Save()
...
// Load saved cookies form cookies/example.site/cookies.json
reqWithCookie := app.Post("https://example.site/cookies")
reqWithCookie.Cookie().Load()
reqWithCookie.Do()
...
Top comments (0)