Using GRequests: A Go Clone of Python Requests for Simplified HTTP Requests

This article introduces the Go library grequests—a clone of Python's requests—demonstrates its installation, compares its API with net/http, and provides concise examples for GET, POST, query strings, basic authentication, and file upload/download, highlighting its simplicity and advantages for HTTP client development.

Go Programming World
Go Programming World
Go Programming World
Using GRequests: A Go Clone of Python Requests for Simplified HTTP Requests

When I switched from Python to Go, I found the built‑in net/http package a bit cumbersome for everyday HTTP work, especially for tasks like POST requests. I discovered grequests, a Go library inspired by Python's popular requests, which aims to make HTTP calls more intuitive. grequests is described as a Go "clone" of the great and famous Requests library, offering a familiar API that reduces the mental overhead of writing HTTP client code.

Below is a minimal net/http GET example for comparison:

// 发起 HTTP GET 请求
resp, _ := http.Get("https://httpbin.org/get")
defer resp.Body.Close() // 确保关闭响应体

// 读取响应体内容
body, _ := io.ReadAll(resp.Body)

// 将响应体打印为字符串
fmt.Println(string(body))

And a net/http POST example, which requires more boilerplate:

// 创建一个要发送的数据结构并编码为 JSON
data := map[string]any{"username": "user", "password": "pass"}
jsonData, _ := json.Marshal(data)

// 创建 POST 请求
url := "https://httpbin.org/post"
request, _ := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonData))
request.Header.Set("Content-Type", "application/json")

// 发送请求并获取响应
client := &http.Client{}
resp, _ := client.Do(request)
defer resp.Body.Close()

// 读取响应体内容
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))

To start using grequests, install it with:

$ go get -u github.com/levigross/grequests

A simple GET request with grequests reduces to three lines:

resp, _ := grequests.Get("https://httpbin.org/get", nil)
defer resp.Close()
fmt.Println(resp)
fmt.Println(resp.String())

Query string parameters can be passed via RequestOptions:

ro := &grequests.RequestOptions{Params: map[string]string{"Hello": "Goodbye"}}
resp, _ := grequests.Get("https://httpbin.org/get?Hello=World", ro)
defer resp.Close()
fmt.Println(resp)
fmt.Println(resp.RawResponse.Request.URL)

The above prints a JSON response showing the final URL https://httpbin.org/get?Hello=Goodbye, demonstrating how Params override existing query values.

Sending a POST request with JSON payload is equally straightforward:

postData := map[string]string{"username": "user", "password": "pass"}
ro := &grequests.RequestOptions{JSON: postData}
resp, _ := grequests.Post("https://httpbin.org/post", ro)
defer resp.Close()
fmt.Println("Response:", resp.String())

Basic authentication can be set using the Auth field:

ro := &grequests.RequestOptions{Auth: []string{"user", "pass"}}
resp, _ := grequests.Get("https://httpbin.org/basic-auth/user/pass", ro)
defer resp.Close()
if resp.Ok != true {
    log.Println("Request did not return OK")
}
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("content-type"))
fmt.Println(resp.String())

m := make(map[string]any)
_ = resp.JSON(&m)
fmt.Println(m)

Downloading a response directly to a file is handled by DownloadToFile:

resp, _ := grequests.Get("https://httpbin.org/get", nil)
defer resp.Close()
_ = resp.DownloadToFile("result.json")

Uploading a file (with optional form data) uses the Files and Data fields:

fd, _ := grequests.FileUploadFromDisk("result.json")
resp, _ := grequests.Post("https://httpbin.org/post", &grequests.RequestOptions{Files: fd, Data: map[string]string{"One": "Two"}})
defer resp.Close()
fmt.Println(resp)

Overall, grequests offers a more elegant and concise API than the standard net/http package, especially for POST requests, query handling, basic authentication, and file transfer, making HTTP client development in Go much more pleasant.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Gofile uploadHTTPAPInet/httpgrequestsrequests clone
Go Programming World
Written by

Go Programming World

Mobile version of tech blog https://jianghushinian.cn/, covering Golang, Docker, Kubernetes and beyond.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.