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"
}
相关推荐
编程版小新1 分钟前
C++初阶:STL详解(四)——vector迭代器失效问题
开发语言·c++·迭代器·vector·迭代器失效
c4fx21 分钟前
Delphi5利用DLL实现窗体的重用
开发语言·delphi·dll
鸽芷咕44 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
Jhxbdks1 小时前
C语言中的一些小知识(二)
c语言·开发语言·笔记
java6666688881 小时前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存1 小时前
源码分析:LinkedList
java·开发语言
代码雕刻家1 小时前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
Fan_web1 小时前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html
liupenglove1 小时前
golang操作mysql利器-gorm
mysql·golang
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机