Req一款Golang封装的Http请求工具

发布时间:阅读数:106


简单使用

简单的使用get,post来请求数据

Get

package main

import (
	"fmt"
	"io"

	"github.com/imroc/req/v3"
)

func main() {
	res, err := req.Get("http://www.httpbin.org/get")
	if err != nil {
		panic(err)
	}
	b, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s", b)
}

Post

package main

import (
	"fmt"
	"io"

	"github.com/imroc/req/v3"
)

func main() {
	res, err := req.Post("http://www.httpbin.org/post")
	if err != nil {
		panic(err)
	}
	b, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s", b)
}

简单使用总结

使用简单的方式无法设置ua,等参数,所以,进行一个拓展

package main

import (
	"fmt"
	"io"

	"github.com/imroc/req/v3"
)

func main() {
	req.SetPathParam("age", "18")
	res, err := req.Get("http://www.httpbin.org/get")
	if err != nil {
		panic(err)
	}
	b, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s", b)
}

链调用

resp := client.Get("https://api.github.com/users/{username}/repos"). // Create a GET request with specified URL.
    SetHeader("Accept", "application/vnd.github.v3+json").
    SetPathParam("username", "imroc").
    SetQueryParam("page", "1").
    SetResult(&result).
    SetError(&errMsg).
    EnableDump().
    Do() // Send request with Do.

if resp.Err != nil {
    // ...
}

对正确错误返回解码

// For testing, you can create and send a request with the global wrapper methods
// that use the default client behind the scenes to initiate the request (you can
// just treat package name `req` as a Client or Request, no need to create any client
// or Request explicitly).
req.DevMode() //  Use Client.DevMode to see all details, try and surprise :)
req.Get("https://httpbin.org/get") // Use Request.Get to send a GET request.

// In production, create a client explicitly and reuse it to send all requests
client := req.C(). // Use C() to create a client and set with chainable client settings.
    SetUserAgent("my-custom-client").
    SetTimeout(5 * time.Second).
    DevMode()
resp, err := client.R(). // Use R() to create a request and set with chainable request settings.
    SetHeader("Accept", "application/vnd.github.v3+json").
    SetPathParam("username", "imroc").
    SetQueryParam("page", "1").
    SetResult(&result). // Unmarshal response into struct automatically if status code >= 200 and <= 299.
    SetError(&errMsg). // Unmarshal response into struct automatically if status code >= 400.
    EnableDump(). // Enable dump at request level to help troubleshoot, log content only when an unexpected exception occurs.
    Get("https://api.github.com/users/{username}/repos")
if err != nil {
    // Handle error.
    // ...
    return
}
if resp.IsSuccess() {
    // Handle result.
    // ...
    return
}
if resp.IsError() {
    // Handle errMsg.	
    // ...
    return
}
// Handle unexpected response (corner case).
err = fmt.Errorf("got unexpected response, raw dump:\n%s", resp.Dump())
// ...

地址: https://github.com/imroc/req


置顶文章
推荐文章