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

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

图片

 

go-resty/resty是一个简单的 HTTP 和 REST 客户端,受到 Ruby rest-client 的启发

文档

  • https://github.com/go-resty/resty/

安装

go get github.com/go-resty/resty/v2

示例

1、发起GET请求

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()))
}

响应结果

{
  "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请求

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()))
}

响应结果

{
  "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"
}

回复:【golang加群】加入golang开发者交流群

回复:【golang资料】获取golang面试刷题资料

图片

golang41

 

 

golang · 目录
上一篇Golang:使用jszwec/csvutil读取csv文件
阅读 159
 
 
 
 
 
 
 
 
 
 
posted @   技术颜良  阅读(639)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2023-05-25 Go 每日一库之 mapstructure
点击右上角即可分享
微信分享提示