Golang:使用go-resty/resty发送http请求get和post

简单的 HTTP 和 REST 客户端,受到 Ruby rest-client 的启发

文档

安装

bash 复制代码
go get github.com/go-resty/resty/v2

示例

1、发起GET请求

go 复制代码
package main

import (
    "fmt"
    "strconv"
    "time"

    "github.com/go-resty/resty/v2"
)

func main() {
    client := resty.New()

    resp, _ := client.R().
        SetQueryParams(map[string]string{
            "page_no": "1",
            "limit":   "20",
            "sort":    "name",
            "order":   "asc",
            "random":  strconv.FormatInt(time.Now().Unix(), 10),
        }).
        SetHeader("Accept", "application/json").
        Get("https://httpbin.org/get")

    fmt.Println(string(resp.Body()))
}

响应结果

json 复制代码
{
  "args": {
    "limit": "20", 
    "order": "asc", 
    "page_no": "1", 
    "random": "1716429557", 
    "sort": "name"
  }, 
  "headers": {
    "Accept": "application/json", 
    "Accept-Encoding": "gzip", 
    "Host": "httpbin.org", 
    "User-Agent": "go-resty/2.13.1 (https://github.com/go-resty/resty)", 
    "X-Amzn-Trace-Id": "Root=1-664ea2f6-429caf50119e71644d6e7fe9"
  }, 
  "origin": "127.0.0.1",
  "url": "https://httpbin.org/get?limit=20&order=asc&page_no=1&random=1716429557&sort=name"
}

2、发送POST请求

go 复制代码
package main

import (
    "fmt"
    "strconv"
    "time"

    "github.com/go-resty/resty/v2"
)

func main() {
    client := resty.New()

    resp, _ := client.R().
        SetBody(map[string]string{
            "page_no": "1",
            "limit":   "20",
            "sort":    "name",
            "order":   "asc",
            "random":  strconv.FormatInt(time.Now().Unix(), 10),
        }).
        Post("https://httpbin.org/post")

    fmt.Println(string(resp.Body()))
}

响应结果

json 复制代码
{
  "args": {}, 
  "data": "{\"limit\":\"20\",\"order\":\"asc\",\"page_no\":\"1\",\"random\":\"1716429749\",\"sort\":\"name\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Content-Length": "78", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "go-resty/2.13.1 (https://github.com/go-resty/resty)", 
    "X-Amzn-Trace-Id": "Root=1-664ea3b6-7b08b8622b633c943a22c362"
  }, 
  "json": {
    "limit": "20", 
    "order": "asc", 
    "page_no": "1", 
    "random": "1716429749", 
    "sort": "name"
  }, 
  "origin": "127.0.0.1",
  "url": "https://httpbin.org/post"
}
相关推荐
gywl1 小时前
openEuler VM虚拟机操作(期末考试)
linux·服务器·网络·windows·http·centos
轻口味1 小时前
命名空间与模块化概述
开发语言·前端·javascript
某柚啊2 小时前
Windows开启IIS后依然出现http error 503.the service is unavailable
windows·http
晓纪同学2 小时前
QT-简单视觉框架代码
开发语言·qt
威桑2 小时前
Qt SizePolicy详解:minimum 与 minimumExpanding 的区别
开发语言·qt·扩张策略
飞飞-躺着更舒服2 小时前
【QT】实现电子飞行显示器(简易版)
开发语言·qt
_oP_i2 小时前
HTTP 请求Media typetext/plain application/json text/json区别
网络协议·http·json
明月看潮生2 小时前
青少年编程与数学 02-004 Go语言Web编程 16课题、并发编程
开发语言·青少年编程·并发编程·编程与数学·goweb
明月看潮生2 小时前
青少年编程与数学 02-004 Go语言Web编程 17课题、静态文件
开发语言·青少年编程·编程与数学·goweb
Java Fans2 小时前
C# 中串口读取问题及解决方案
开发语言·c#