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"
}
相关推荐
励志成为嵌入式工程师39 分钟前
c语言简单编程练习9
c语言·开发语言·算法·vim
捕鲸叉1 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer1 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
Peter_chq1 小时前
【操作系统】基于环形队列的生产消费模型
linux·c语言·开发语言·c++·后端
记录成长java3 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet
前端青山3 小时前
Node.js-增强 API 安全性和性能优化
开发语言·前端·javascript·性能优化·前端框架·node.js
睡觉谁叫~~~3 小时前
一文解秘Rust如何与Java互操作
java·开发语言·后端·rust
音徽编程3 小时前
Rust异步运行时框架tokio保姆级教程
开发语言·网络·rust
观音山保我别报错3 小时前
C语言扫雷小游戏
c语言·开发语言·算法
小屁孩大帅-杨一凡4 小时前
java后端请求想接收多个对象入参的数据
java·开发语言