SoFunction
Updated on 2025-04-13

Detailed explanation of the use of the most convenient http request package resty in Go language

Although the go language has its own net/http package, it is not that easy to use. The resty package is a very popular http request processing package in the Go language. Its API is very concise, one can understand it at a glance, and is very friendly to novices. It supports chain calls, timeouts, retry mechanisms, and supports middleware. It can do some operations before and after the request is sent, which is very comfortable to use. Let’s take a look together today.

Install

Let's install it firstgo get /go-resty/resty/v2

1. A simple get

Try sending a get request?

package main

import (
	"fmt"

	"/go-resty/resty/v2"
)

func main() {
	client := ()

	resp, err := ().
		Get("")

	if err != nil {
		("Request error:", err)
		return
	}

	("Status Code:", ())
	("Response:", ())
	("Response header:", ())                       // Get all headers	("Specific response header:", ().Get("Content-Type")) // Get a specific header	// Status code: 200	// Response body: too many xxx and omit it...	// Response header: map[Accept-Ranges:[bytes] Cache-Control:[no-cache] Connection:[keep-alive] Content-Length:[227] Content-Security-Policy:[frame-ancestors 'self' ;] Content-Type:[text/html] Date:[Sun, 16 Mar 2025 09:43:18 GMT] P3p:[CP=" OTI DSP COR IVA OUR IND COM "]  Pragma:[no-cache] Server:[BWS/1.1] Set-Cookie:[BD_NOT_HTTPS=1; path=/; Max-Age=300 BIDUPSID=10846246655E82CCF356A792677D7EA8; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=. PSTM=1742118198; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/;  domain=. BAIDUID=10846246655E82CC89D4B0052594BBBE:FG=1; max-age=31536000; expires=Mon, 16-Mar-26 09:43:18 GMT; domain=.; path=/; version=1; comment=bd] Traceid:[1742118198045022490612843349543995319034] X-Ua-Compatible:[IE=Edge,chrome=1] X-Xss-Protection:[1;mode=block]]	// Specific response header: text/html}

It supports chain calls, the only thing to note is **Request method + pathTo put it last - it returns the response**.

2. With query parameters

resp, err := ().
	SetQueryParam("postId", "1"). // Setting a single query parameter is also OK	Get("/posts")

// resp, err := ().
// SetQueryParams(map[string]string{ // Set multiple query parameters// 		"postId": "1",
// 	}).
// 	Get("/posts")

It supports setting multiple query parameters at onceSetQueryParams, and single query parametersSetQueryParamTwo ways.

3. Set request header and body

Since chain calls are supported, setting request headers is also very convenient

	resp, err := ().
		SetHeader("Content-Type", "application/json"). // Set a single request header		SetBody(`{"title": "foo", "body": "bar", "userId": 1}`). // String form		Post("/posts")

	resp, err := ().
		SetBody(map[string]interface{}{ // Support map structure			"title":  "foo",
			"body":   "bar",
			"userId": 1,
		}).
		SetHeaders(map[string]string{  // Set multiple request headers			"Content-Type": "application/json",
		}).
		Post("/posts")

	resp, err := ().
		SetBody(Post{Title: "foo", Body: "bar", UserId: 1}). // Support struct		SetHeaders(map[string]string{
			"Content-Type": "application/json",
		}).
		Post("/posts")

	// Create from file	file, err := ("my_file.txt")
	if err != nil {
			// ... Error handling ...	}
	defer ()
	resp, err := ().
			// It is OK to not set. Resty will automatically infer content-type based on the reader			SetHeader("Content-Type", "application/octet-stream"). // Or set according to file type			SetBody(file). // Support method			Post("/upload")
  • SetBodyVery rich support methodsjson stringmapstruct[]byte
  • Setting the request header is similar to the previous setting query parameters, and supports single and multiplePlural sTwo ways.

4. Set form data

resp, err := ().
		SetFormData(map[string]string{"title": "foo", "body": "bar", "userId": "1"}).
		Post("/posts")

Need to pay attentionSetFormDataParameters are only supportedmap[string]stringtype.

5. Processing response

// ask	type postReq struct {
		Title  string `json:"title"`
		Body   string `json:"body"`
		UserId int    `json:"userId"`
	}

	// Response	type postRes struct {
		ID     int    `json:"id"`
		Title  string `json:"title"`
		Body   string `json:"body"`
		UserId int    `json:"userId"`
	}

	var pr postRes

	resp, err := ().
		SetHeader("Content-Type", "application/json").
		SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
		SetResult(&pr). // Set the content after the response		Post("/posts")

	if err != nil {
		("Request error:", err)
		return
	}

	("Has the request succeeded?", ()) // Whether it responds	("Response result:%#v\n", pr)
	// Is the request successful?  true	// Response result: {ID:101, Title:"foo", Body:"bar", UserId:1}
  • IsSuccessDetermine whether the response is
  • SetResultSupport mapping response results into structures

6. Timeout and retry

	client := ().
		SetTimeout(5 * ).          // Set the timeout time		SetRetryCount(3).                     // Set the number of retry to 3		SetRetryWaitTime(1 * ).    // Set the retry interval to 1 second		SetRetryMaxWaitTime(5 * ). //Maximum retry interval		AddRetryCondition(
			func(r *, err error) bool {
				return () ==  // 429 Try again when error			},
		)

	resp, err := ().
		SetHeader("Content-Type", "application/json").
		SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
		SetResult(&pr).
		Post("/posts")

One thing that needs()and the following()It is a different class. The former is mainly used to set globally related settings (such as timeout, retry, etc.); the latter is mainly used to set requests to send related settings;

7. Debugging mode

resp, err := ().
		SetHeader("Content-Type", "application/json").
		SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
		SetResult(&pr).
		SetDebug(true). // Turn on debug mode		Post("/posts")

Debugging mode is enabled, and all the requested parameters and response content can be seen.

8. Middleware

client := ()

// Request middleware(func(c *, req *) error {
	("Before sending a request:", )
	// You can modify the request, for example ("New-Header", "value")	return nil
})

// Response middleware(func(c *, resp *) error {
	("After receiving the response:", ())
	return nil
})

resp, err := ().
	SetHeader("Content-Type", "application/json").
	SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
	SetResult(&pr).
	Post("/posts")

It also supports middleware, and does some processing before and after sending a request.

This is the article about the detailed explanation of the most convenient http request package resty in Go language. For more relevant content on using Go, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!