SoFunction
Updated on 2025-03-05

Introduction and basic use of Requests in Go standard library

1. Introduction

Official Document DOC://levigross/grequests

Github: /levigross/grequests

In PythonRequestsThe library is very powerful, so Go developers imitate Python'sRequestsThe library was bornGrequestslibrary.GrequestsIt provides a series of convenient functions, making sending HTTP requests simple and efficient. Here isGrequestsSome key features implemented in Golang:

  • Response serializationGrequestsSupports serializing HTTP response content into JSON and XML formats, making it more convenient to process API responses.
  • File upload and download: Provides a convenient way to upload and download files without complicated configuration.
  • HTTP verb support: Supports a wide range of HTTP verbs, including GET, HEAD, POST, PUT, DELETE, PATCH, and OPTIONS, which can cover most HTTP request scenarios.

2. Installation

To get started with the Grequests library, you need to install it in your Go environment first. The installation can be completed through the following command:

go get -u /levigross/grequests

3. Import

After installing Grequests, you can import it into your Go code via the import statement:

import "/levigross/grequests"

4. Basic use

4.1 Send a GET request

Here is an example of sending a GET request, which demonstrates how to get an HTTP response and print it out:

func Get() {
	resp, err := ("http://127.0.0.1:8080/book/", nil)
	if err != nil {
		("Unable to make request: ", err)
	}

	if ! {
		("Request timed out!")
	}

	// parse the response's JSON data	var data []map[string]interface{}
	if err := (&data); err != nil {
		("Unable to parse JSON response: ", err)
	}
	(data)
}

The above code is first usedGetThe method sends a GET request and then checks for errors to occur. If there is no error, you can pass()Method to get the text content of the response.

4.2 POST request to send JSON data

In the following example, we create a map object to hold the JSON data we want to send. Then we passROptionA request option object is created, and there is specified JSON as the sent data type. Finally, we callPostMethod to send a request:

func Post() {
	postData := map[string]string{
		"id":   "1",
		"name": "Go to Advanced",
	}
	geq := &{
		JSON: postData,
	}
	resp, err := ("http://127.0.0.1:8080/book/create", geq)
	if err != nil {
		("Unable to make request: ", err)
	}
	(())
}

Here is a line-by-line explanation of the code:

postData := map[string]string{"id": "1", "name": "Go to Advanced"}

Here is amap[string]stringVariables of typepostData, which contains two key-value pairs, name, respectively, and their values ​​are "1" and "Go Beginner to Advanced".

geq := &{JSON: postData}

A created hereVariables of typegeqIt is a structure used to configure various options for HTTP requests, such as URL, method, header information, data, etc. In this example, weJSONThe field willpostDataPass as JSON data to the POST request.

resp, err := ("http://127.0.0.1:8080/book/create", geq)

Called hereThe function initiates a POST request.http://127.0.0.1:8080/book/createis the requested target URL, andgeqis the requested configuration option.The function will return aResponseobject and a possible error.

if err != nil { ("Unable to make request: ", err) }

ifAn error occurred while calling the function, and this conditional block will be executed.The function prints an error message and exits the program.

(())

If the request is successful, this conditional block will be executed.()The method returns the string representation of the response body and then usesThe function prints it to standard output.

In general, the function of this code is to the local server (assuming that127.0.0.1:8080)/book/createThe path sends a POST request, the request body is JSON format data, containing an ID and book title. If the request succeeds, it prints out the server's response. If the request fails, it prints out an error message and exits the program.

4.3 Post file upload

File upload is equally simple. You can passRequestOptionsSpecify file:

func UploadFile() {
	// Allows you to create FileUpload structure slices by specifying the location on the disk	// Open the file to be uploaded	file, err := ("./")
	if err != nil {
		("Unable to open file: ", err)
	}
	defer ()

	// Create FileUpload structure slice	ro := &{
		Files: []{{
			FileName:     "", // Uploaded file name			FieldName:    "file",  // Upload the corresponding fields of the file			FileContents: file, // Use file content as FileContents		}},
	}
	// Send POST request	resp, err := ("http://127.0.0.1:8080/book/upload/", ro)
	if err != nil {
		("Unable to make request: ", err)
	}
	(())
}

In the above code, we create aFileUploadStructure, throughFileNameFieldNameandFileContentsLet's specify the details of the file we want to upload.

4.4 GoRequests Using Proxy

gorequestAgent, here is a simple example, you need toProxiesThe URL in it is added as*acting:

func Proxy() {
	// Proxy server	const proxyServer = ":9010"

	// Proxy tunnel verification information	const proxyUser = "xxxxxxxxx"
	const proxyPass = "xxxxxxxxx"

	// Initialize the proxy URL	proxyUrl, _ := ("http://" + proxyUser + ":" + proxyPass + "@" + proxyServer)

	// Create request option	ro := &{
		Proxies: map[string]*{
			"http": proxyUrl,
		},
		Headers: map[string]string{
			"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
		},
	}

	// Initiate a GET request	resp, err := ("", ro)
	if err != nil {
		("Error:", err)
		return
	}

	// Print the response status code	("Status code:", )

	// Print the response body	("Response:", ())
}

Here is a line-by-line explanation of the code:

// Proxy server

This line is a comment that declares that the following code will define the URL of the proxy server.

const proxyServer = ":9010"

A constant is defined hereproxyServer, its value is the URL of the proxy server, in the formathttp://host:port

// Proxy tunnel verification information

This line is a comment that declares that the following code will define the verification information for the proxy tunnel.

const proxyUser = "xxxxxxxxx"

A constant is defined hereproxyUser, its value is the username of the proxy tunnel.

const proxyPass = "xxxxxxxxx"

A constant is defined hereproxyPass, its value is the password of the proxy tunnel.

// Initialize the proxy URL

This line is a comment that the following code will create the proxy URL.

proxyUrl, _ := ("http://" + proxyUser + ":" + proxyPass + "@" + proxyServer)

This line of code usesThe function creates a proxy URL. It combines the username, password and proxy server address of the proxy tunnel into a URL in the formathttp://username:password@host:port_is a convention to ignore the return value, because the return value is usually not required.

// Create request option

This line is a comment that the following code will create aStructure for configuring HTTP requests.

ro := &{

Definition begins hereStructural variablesro

Proxies: map[string]*{

It's defined hereProxiesField, it is a map that maps protocols (such as "http") to proxy URLs.

"http": proxyUrl,

This line of code sets the proxy URL to the proxy for the HTTP protocol.

},

This is the end of the mapping definition.

Headers: map[string]string{

It's defined hereHeadersField, which is a map that maps HTTP header fields (such as "user-agent") to the corresponding value.

"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",

This line of code sets an HTTP header field, namely the User-Agent, to identify the client that initiated the request.

},

This is the end of the mapping definition.

}

This isThe definition of structure variable ends.

// Initiate a GET request

This line is a comment that the following code will initiate a GET request.

resp, err := ("", ro)

This line of code usesThe function initiates a GET request.is the requested target URL, androis the requested configuration option.The function will return aResponseobject and a possible error.

if err != nil {

ifAn error occurred while calling the function, and this conditional block will be executed.

("Error:", err)

This line of code prints out an error message.

return

This line of code means that if an error occurs, the function will return and will not continue to execute.

}

This is the end of the error handling block.

("Status code:", )

If the request is successful, this line of code will print out the status code of the response.

("Response:", ())

4.5 Gorequests Using session

Here is an example of using Session:

session := {
		RequestOptions: &{
			Headers: map[string]string{
				"authority":  "mp3.",
				"referer":    "https:///",
				"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
			},
		},
	}

5. HTTP server code

package main

import (
	"encoding/json"
	"/gin-gonic/gin"
	"net/http"
	"os"
)

type Book struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type BookHandler struct {
}

func (b *BookHandler) RegisterRoutes(server *) {
	bg := ("/book")
	("/upload", )
	("/create", )
	("/", ) // Inquiry of books}

func (b *BookHandler) Upload(ctx *) {
	// Get file from request	file, err := ("file")
	if err != nil {
		(, {"error": "Uploaded file cannot be obtained"})
		return
	}

	// Save the file to the server	// Note: Here you need to make sure that the directory where the file is saved exists and that the server has write permissions	savePath := "./uploads/" + 
	if err := (file, savePath); err != nil {
		(, {"error": "File saving failed"})
		return
	}

	(, {"message": "File upload successfully"})
}

func (b *BookHandler) Create(ctx *) {
	var req Book
	if err := (&req); err != nil {
		return
	}

	// Save new book data to a file	if err := addBookToFile(&req); err != nil {
		(, {"error": "Failed to save book data"})
		return
	}

	(, {"message": "Book added successfully"})
}
func (b *BookHandler) GetAllBooks(c *) {
	// Read book data from a file	books, err := getBooksFromFile()
	if err != nil {
		(, {"error": "Failed to read book data"})
		return
	}

	// Get the id in the URL query parameter	id := ("id")

	// If an ID is provided, find a list of books with matching IDs	if id != "" {
		// Find books with matching IDs		var foundBooks []Book
		for _, book := range books {
			if  == id {
				foundBooks = append(foundBooks, book)
			}
		}
		// If a matching book is found, return to these books		if len(foundBooks) > 0 {
			(, foundBooks)
			return
		}
		// If no matching book is found, return 404		(, {"error": "Books not found"})
		return
	}

	// If no ID is provided, return all books	(, books)
}
func addBookToFile(book *Book) error {
	// Read existing file contents	var books []Book
	data, err := ("")
	if err != nil && !(err) {
		return err
	}

	// If the file exists, parse the existing book data	if err == nil {
		if err := (data, &books); err != nil {
			return err
		}
	}

	// Add new books to the array	books = append(books, *book)

	// Serialize the updated book array to JSON	newData, err := (books, "", "    ")
	if err != nil {
		return err
	}

	// Write serialized JSON data to a file	if err := ("", newData, 0644); err != nil {
		return err
	}

	return nil
}
func getBooksFromFile() ([]Book, error) {
	// Read file content	data, err := ("")
	if err != nil {
		return nil, err
	}

	// parse JSON data into book array	var books []Book
	if err := (data, &books); err != nil {
		return nil, err
	}

	return books, nil
}

func InitWebServer(bookHandler *BookHandler) * {
	server := ()
	(server)
	return server
}

func main() {
	// Make sure the upload directory exists	("./uploads", 0755)

	bookHandler := &BookHandler{}
	server := InitWebServer(bookHandler)
	(":8080") // Start the server on port 8080}

The above is the introduction and basic usage of Requests in the Go standard library. For more information about Go Requests, please pay attention to my other related articles!