Skip to content

Commit 7c49de6

Browse files
committed
add lo req examples
1 parent 0c44fdb commit 7c49de6

File tree

5 files changed

+147
-2
lines changed

5 files changed

+147
-2
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ require (
77
github.com/gin-contrib/static v1.1.2
88
github.com/google/go-cmp v0.6.0
99
github.com/google/uuid v1.6.0
10-
github.com/imroc/req/v3 v3.43.7
10+
github.com/imroc/req/v3 v3.44.0
1111
github.com/itchyny/gojq v0.12.16
1212
github.com/joho/godotenv v1.5.1
1313
github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,8 @@ github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec h1:qv2VnGeEQHchGaZ/u
194194
github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68=
195195
github.com/imroc/req/v3 v3.43.7 h1:dOcNb9n0X83N5/5/AOkiU+cLhzx8QFXjv5MhikazzQA=
196196
github.com/imroc/req/v3 v3.43.7/go.mod h1:SQIz5iYop16MJxbo8ib+4LnostGCok8NQf8ToyQc2xA=
197+
github.com/imroc/req/v3 v3.44.0 h1:JBrxoN5DykYvkeEZx3dski8/A+WVz9HD147cwEeyFlM=
198+
github.com/imroc/req/v3 v3.44.0/go.mod h1:6cQ91w7qPn+bYjcWnA1S/LmTh6z3cz8Oa9qdwm7gS8w=
197199
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
198200
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
199201
github.com/itchyny/gojq v0.12.16 h1:yLfgLxhIr/6sJNVmYfQjTIv0jGctu6/DgDoivmxTr7g=

internal/utils/qhttp/client.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,13 @@ func NewHttpClient() *Client {
1818
}
1919
}
2020

21-
func (h Client) Get(url string) (string, string, *req.Response) {
21+
func (h *Client) Get(url string) (string, string, *req.Response) {
2222
resp := h.Client.R(). // Use R() to create a request.
2323
MustGet(url)
2424
return resp.Status, resp.String(), resp
2525
}
26+
27+
func (h *Client) DebugOptions() {
28+
req.EnableAutoDecode()
29+
req.EnableDebugLog()
30+
}

internal/utils/qhttp/client_test.go

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
package qhttp
22

3+
//https://github.com/imroc/req
4+
35
import (
46
"fmt"
7+
"github.com/imroc/req/v3"
8+
"log"
59
"testing"
10+
"time"
611
)
712

813
const MD = "https://raw.githubusercontent.com/luban-agi/Awesome-AIGC-Tutorials/main/README.md"
@@ -16,3 +21,124 @@ func TestHttpClient_Get(t *testing.T) {
1621
fmt.Println(statusCode, md)
1722
fmt.Println(statusCode1, md_zh)
1823
}
24+
25+
func TestReqMode(t *testing.T) {
26+
req.DevMode()
27+
req.EnableAutoDecode()
28+
req.EnableForceHTTP1()
29+
var result = req.MustGet("https://httpbin.org/uuid")
30+
print(result)
31+
}
32+
33+
type ErrorMessage struct {
34+
Message string `json:"message"`
35+
}
36+
37+
func (msg *ErrorMessage) Error() string {
38+
return fmt.Sprintf("API Error: %s", msg.Message)
39+
}
40+
41+
type UserInfo struct {
42+
Name string `json:"name"`
43+
Blog string `json:"blog"`
44+
}
45+
46+
func TestAdvancedUsage(t *testing.T) {
47+
client := req.C().
48+
SetUserAgent("my-custom-client"). // Chainable client settings.
49+
SetTimeout(5 * time.Second).
50+
OnAfterResponse(func(client *req.Client, resp *req.Response) error {
51+
if resp.Err != nil { // There is an underlying error, e.g. network error or unmarshal error.
52+
return nil
53+
}
54+
if errMsg, ok := resp.ErrorResult().(*ErrorMessage); ok {
55+
resp.Err = errMsg // Convert api error into go error
56+
return nil
57+
}
58+
if !resp.IsSuccessState() {
59+
// Neither a success response nor a error response, record details to help troubleshooting
60+
resp.Err = fmt.Errorf("bad status: %s\nraw content:\n%s", resp.Status, resp.Dump())
61+
}
62+
return nil
63+
})
64+
65+
var userInfo UserInfo
66+
var errMsg ErrorMessage
67+
resp, err := client.R().
68+
SetHeader("Accept", "application/vnd.github.v3+json"). // Chainable request settings.
69+
SetPathParam("username", "imroc"). // Replace path variable in url.
70+
SetSuccessResult(&userInfo). // Unmarshal response body into userInfo automatically if status code is between 200 and 299.
71+
SetErrorResult(&errMsg). // Unmarshal response body into errMsg automatically if status code >= 400.
72+
EnableDump(). // Enable dump at request level, only print dump content if there is an error or some unknown situation occurs to help troubleshoot.
73+
Get("https://api.github.com/users/{username}")
74+
75+
if err != nil { // Error handling.
76+
log.Println("error:", err)
77+
log.Println("raw content:")
78+
log.Println(resp.Dump()) // Record raw content when error occurs.
79+
return
80+
}
81+
82+
if resp.IsErrorState() { // Status code >= 400.
83+
fmt.Println(errMsg.Message) // Record error message returned.
84+
return
85+
}
86+
87+
if resp.IsSuccessState() { // Status code is between 200 and 299.
88+
fmt.Printf("%s (%s)\n", userInfo.Name, userInfo.Blog)
89+
return
90+
}
91+
92+
// Unknown status code.
93+
log.Println("unknown status", resp.Status)
94+
log.Println("raw content:")
95+
log.Println(resp.Dump()) // Record raw content when server returned unknown status code.
96+
}
97+
98+
type Repo struct {
99+
Name string `json:"name"`
100+
Url string `json:"url"`
101+
}
102+
103+
type Result struct {
104+
Data string `json:"data"`
105+
}
106+
107+
func TestSimplePost(t *testing.T) {
108+
client := req.C().DevMode()
109+
var result Result
110+
111+
resp, err := client.R().
112+
SetBody(&Repo{Name: "req", Url: "https://github.com/imroc/req"}).
113+
SetSuccessResult(&result).
114+
Post("https://httpbin.org/post")
115+
if err != nil {
116+
log.Fatal(err)
117+
}
118+
119+
if !resp.IsSuccessState() {
120+
fmt.Println("bad response status:", resp.Status)
121+
return
122+
}
123+
fmt.Println("++++++++++++++++++++++++++++++++++++++++++++++++")
124+
fmt.Println("data:", result.Data)
125+
fmt.Println("++++++++++++++++++++++++++++++++++++++++++++++++")
126+
}
127+
128+
type APIResponse struct {
129+
Origin string `json:"origin"`
130+
Url string `json:"url"`
131+
}
132+
133+
func TestApiStyleReq(t *testing.T) {
134+
var resp APIResponse
135+
c := req.C().SetBaseURL("https://httpbin.org/post")
136+
err := c.Post().
137+
SetBody("hello").
138+
Do().
139+
Into(&resp)
140+
if err != nil {
141+
panic(err)
142+
}
143+
fmt.Println("My IP is", resp.Origin)
144+
}

internal/utils/structs.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package utils
22

33
import (
44
"fmt"
5+
"github.com/samber/lo"
56
"reflect"
7+
"strings"
68
)
79

810
// StructToMap : returns a map of names to values for struct passed .
@@ -37,3 +39,13 @@ func CopyToStringStruct(src interface{}, dest interface{}) {
3739
newField.SetString(fmt.Sprintf("%v", srcField.Interface()))
3840
}
3941
}
42+
43+
func FilterStringMap(mapping []string, key string) []string {
44+
matching := lo.FilterMap(mapping, func(x string, _ int) (string, bool) {
45+
if strings.HasSuffix(x, key) {
46+
return x, true
47+
}
48+
return "", false
49+
})
50+
return matching
51+
}

0 commit comments

Comments
 (0)