golang简洁易用的REST API客户端插件库rclient的使用
Golang简洁易用的REST API客户端插件库rclient的使用
RClient简介
RClient是一个简洁易用的Golang REST API客户端库,它提供了简单的方式来与RESTful API进行交互。
快速开始
以下是一个使用RClient与GitHub API交互的示例:
package main
import (
"github.com/zpatrick/rclient"
"log"
)
// 定义Repository结构体
type Repository struct {
Name string `json:"name"`
}
func main() {
// 创建REST客户端,指定基础URL
client := rclient.NewRestClient("https://api.github.com")
// 定义接收结果的变量
var repos []Repository
// 发送GET请求获取用户zpatrick的仓库列表
if err := client.Get("/users/zpatrick/repos", &repos); err != nil {
log.Fatal(err)
}
// 打印结果
log.Println(repos)
}
请求选项
请求可以通过RequestOption
进行配置,它是一个操作http.Request
的函数。
自定义请求选项示例
// 设置HTTP协议版本为1.0的自定义选项
setProto := func(req *http.Request) error {
req.Proto = "HTTP/1.0"
return nil
}
// 使用自定义选项发送GET请求
client.Get("/path", &v, setProto)
内置请求选项
Header / Headers
Header()
和Headers()
选项用于添加请求头:
// 添加单个请求头
client.Get("/path", &v, rclient.Header("name", "val"))
// 添加多个请求头
client.Get("/path", &v, rclient.Header("name1", "val1"), rclient.Header("name2", "val2"))
client.Get("/path", &v, rclient.Headers(map[string]string{"name1": "val1", "name2":"val2"}))
Basic Auth
BasicAuth()
选项用于添加基本认证:
client.Get("/path", &v, rclient.BasicAuth("user", "pass"))
Query
Query()
选项用于添加查询参数:
query := url.Values{}
query.Add("name", "John")
query.Add("age", "35")
client.Get("/path", &v, rclient.Query(query))
注意:也可以通过直接在路径中添加查询参数来实现:
client.Get("/path?name=John&age=35", &v)
客户端配置
RestClient
可以通过以下客户端选项进行配置:
Doer
Doer()
选项设置RestClient
的RequestDoer
字段,默认是http.DefaultClient
:
client, err := rclient.NewRestClient("https://api.github.com", rclient.Doer(&http.Client{}))
Request Options
RequestOptions()
选项设置RestClient
的RequestOptions
字段,可以应用于所有请求:
options := []rclient.RequestOption{
rclient.Header("name", "John Doe"),
rclient.Header("token", "abc123"),
}
client, err := rclient.NewRestClient("https://api.github.com", rclient.RequestOptions(options...))
Builder
Builder()
选项设置RestClient
的RequestBuilder
字段,用于构建*http.Request
对象:
builder := func(method, url string, body interface{}, options ...RequestOption) (*http.Request, error){
req, _ := http.NewRequest(method, url, nil)
for _, option := range options {
if err := option(req); err != nil {
return nil, err
}
}
return nil, errors.New("I forgot to add a body to the request!")
}
client, err := rclient.NewRestClient("https://api.github.com", rclient.Builder(builder))
Reader
Reader()
选项设置RestClient
的ResponseReader
字段,用于读取*http.Response
对象:
reader := func(resp *http.Response, v interface{}) error{
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(v)
}
client, err := rclient.NewRestClient("https://api.github.com", rclient.Reader(reader))
许可证
该项目使用MIT许可证发布。
更多关于golang简洁易用的REST API客户端插件库rclient的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang简洁易用的REST API客户端插件库rclient的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
rclient - Golang简洁易用的REST API客户端库
rclient是一个轻量级的Golang REST API客户端库,它提供了简洁的API和强大的功能,让HTTP请求变得更加简单直观。下面我将介绍rclient的主要特性和使用方法。
主要特性
- 简洁的链式调用API
- 自动JSON序列化/反序列化
- 请求/响应拦截器
- 内置重试机制
- 超时和上下文支持
- 自定义HTTP客户端
安装
go get github.com/go-resty/resty/v2
注意:虽然提问中提到了"rclient",但实际在Go生态中,resty是最流行的轻量级REST客户端库之一,功能与描述相符。
基本使用示例
package main
import (
"fmt"
"log"
"github.com/go-resty/resty/v2"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
client := resty.New()
// GET请求示例
var user User
resp, err := client.R().
SetResult(&user).
Get("https://jsonplaceholder.typicode.com/users/1")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Status: %d\n", resp.StatusCode())
fmt.Printf("User: %+v\n", user)
// POST请求示例
newUser := User{
Name: "John Doe",
Email: "john@example.com",
}
var createdUser User
resp, err = client.R().
SetBody(newUser).
SetResult(&createdUser).
Post("https://jsonplaceholder.typicode.com/users")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created User: %+v\n", createdUser)
}
高级功能
1. 设置请求头
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer token123").
Get("https://api.example.com/data")
2. 查询参数
resp, err := client.R().
SetQueryParams(map[string]string{
"page": "1",
"limit": "20",
}).
Get("https://api.example.com/users")
3. 错误处理
resp, err := client.R().
SetError(&apiError{}).
Get("https://api.example.com/data")
if err != nil {
// 网络错误等
log.Fatal(err)
}
if resp.IsError() {
// HTTP状态码错误
err := resp.Error().(*apiError)
fmt.Printf("API Error: %+v\n", err)
}
4. 超时设置
client.SetTimeout(5 * time.Second)
5. 重试机制
client.
SetRetryCount(3).
SetRetryWaitTime(1 * time.Second).
SetRetryMaxWaitTime(5 * time.Second)
6. 拦截器
// 请求前拦截器
client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
fmt.Printf("Sending request to %s\n", req.URL)
return nil
})
// 响应后拦截器
client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
fmt.Printf("Received response with status %d\n", resp.StatusCode())
return nil
})
完整示例
package main
import (
"fmt"
"log"
"time"
"github.com/go-resty/resty/v2"
)
type Post struct {
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
UserID int `json:"userId"`
}
type APIError struct {
Message string `json:"message"`
Code int `json:"code"`
}
func main() {
client := resty.New().
SetHostURL("https://jsonplaceholder.typicode.com").
SetTimeout(5 * time.Second).
SetRetryCount(3).
OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
fmt.Printf("Request: %s %s\n", req.Method, req.URL)
return nil
}).
OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
fmt.Printf("Response: %d %s\n", resp.StatusCode(), resp.Time())
return nil
})
// 获取帖子列表
var posts []Post
_, err := client.R().
SetResult(&posts).
SetQueryParam("userId", "1").
Get("/posts")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Got %d posts\n", len(posts))
// 创建新帖子
newPost := Post{
Title: "New Post",
Body: "This is the body of the new post",
UserID: 1,
}
var createdPost Post
_, err = client.R().
SetBody(newPost).
SetResult(&createdPost).
SetError(&APIError{}).
Post("/posts")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created post: %+v\n", createdPost)
}
总结
rclient(resty)提供了简洁而强大的API来处理REST请求,它的链式调用方式让代码更加清晰易读。通过这个库,你可以轻松实现:
- 各种HTTP方法的请求
- 自动的JSON序列化/反序列化
- 灵活的请求配置
- 完善的错误处理
- 可扩展的拦截器机制
对于需要与REST API交互的Golang项目,rclient(resty)是一个非常值得考虑的选择。