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"
}
相关推荐
夏天的味道٥2 小时前
使用 Java 执行 SQL 语句和存储过程
java·开发语言·sql
IT、木易3 小时前
大白话JavaScript实现一个函数,将字符串中的每个单词首字母大写。
开发语言·前端·javascript·ecmascript
Mr.NickJJ4 小时前
JavaScript系列06-深入理解 JavaScript 事件系统:从原生事件到 React 合成事件
开发语言·javascript·react.js
Archer1945 小时前
C语言——链表
c语言·开发语言·链表
My Li.5 小时前
c++的介绍
开发语言·c++
功德+n6 小时前
Maven 使用指南:基础 + 进阶 + 高级用法
java·开发语言·maven
达斯维达的大眼睛6 小时前
qt小项目,简单的音乐播放器
开发语言·qt
面会菜.6 小时前
C语言(队列)
c语言·开发语言
内核程序员kevin6 小时前
Go+eBPF kprobe 禁止运行指定程序
golang·ebpf·kprobe
香精煎鱼香翅捞饭6 小时前
java通用自研接口限流组件
java·开发语言