Golang:使用go-resty/resty傳送http請求get和post

技术颜良發表於2024-05-25

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

相關文章