http tool get

This commit is contained in:
xing 2023-10-04 21:48:21 +08:00
parent 2302aa7ff8
commit 21a4ff3b3e
4 changed files with 141 additions and 0 deletions

View File

@ -126,3 +126,11 @@ func FileExist(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func GetAnyVal[T any](v any, defaults T) T {
vv, ok := v.(T)
if !ok {
return defaults
}
return vv
}

View File

@ -267,3 +267,16 @@ func TestGetValFromContext(t *testing.T) {
})
}
}
func TestGetAnyVal(t *testing.T) {
t.Run("string", func(t *testing.T) {
want := "string"
if got := GetAnyVal(any("string"), "s"); !reflect.DeepEqual(got, want) {
t.Errorf("GetAnyVal() = %v, want %v", got, want)
}
want = "s"
if got := GetAnyVal(any(1), "s"); !reflect.DeepEqual(got, want) {
t.Errorf("GetAnyVal() = %v, want %v", got, want)
}
})
}

69
helper/httptool/http.go Normal file
View File

@ -0,0 +1,69 @@
package httptool
import (
"io"
"net/http"
"net/url"
"time"
)
func GetString(u string, q map[string]string, timeout int64, a ...any) (r string, code int, err error) {
res, err := Get(u, q, timeout, a...)
if res != nil {
code = res.StatusCode
}
if err != nil {
return "", code, err
}
defer res.Body.Close()
rr, err := io.ReadAll(res.Body)
if err != nil {
return "", code, err
}
r = string(rr)
return
}
func Get(u string, q map[string]string, timeout int64, a ...any) (res *http.Response, err error) {
parse, err := url.Parse(u)
if err != nil {
return nil, err
}
cli := http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
values := parse.Query()
for k, v := range q {
values.Add(k, v)
}
parse.RawQuery = values.Encode()
req := http.Request{
Method: "GET",
URL: parse,
}
if len(a) > 0 {
for _, arg := range a {
h, ok := arg.(map[string]string)
if ok && len(h) > 0 {
for k, v := range h {
req.Header.Add(k, v)
}
}
t, ok := arg.(time.Duration)
if ok {
cli.Timeout = t
}
checkRedirect, ok := arg.(func(req *http.Request, via []*http.Request) error)
if ok {
cli.CheckRedirect = checkRedirect
}
jar, ok := arg.(http.CookieJar)
if ok {
cli.Jar = jar
}
}
}
res, err = cli.Do(&req)
return
}

View File

@ -0,0 +1,51 @@
package httptool
import (
"testing"
)
func TestGetString(t *testing.T) {
type args struct {
u string
q map[string]string
timeout int64
a []any
}
tests := []struct {
name string
args args
wantR string
wantCode int
wantErr bool
}{
{
name: "wp.test",
args: args{
u: "http://wp.test",
q: map[string]string{
"p": "2",
"XDEBUG_SESSION_START": "34343",
},
timeout: 3,
},
wantR: `{"XDEBUG_SESSION_START":"34343","p":"2"}`,
wantCode: 200,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotR, gotCode, err := GetString(tt.args.u, tt.args.q, tt.args.timeout, tt.args.a...)
if (err != nil) != tt.wantErr {
t.Errorf("GetString() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotR != tt.wantR {
t.Errorf("GetString() gotR = %v, want %v", gotR, tt.wantR)
}
if gotCode != tt.wantCode {
t.Errorf("GetString() gotCode = %v, want %v", gotCode, tt.wantCode)
}
})
}
}