Hasaki
http request library for golang
- Package
github.com/lxzan/hasaki
基本使用
发送GET请求
package main
import (
"github.com/lxzan/hasaki"
)
func main() {
result := make([]map[string]interface{}, 0)
err := hasaki.
Get("https://api.github.com/users/%s/repos", "lxzan").
SetQuery(hasaki.Any{
"type": "go",
"per_page": 1,
}).
Send(nil).
BindJSON(&result)
}
发送POST JSON请求
func main() {
var body = struct {
Name string `json:"name"`
}{Name: "caster"}
err := hasaki.
Post("http://localhost:8080" + "/sendJson").
SetEncoder(hasaki.JsonEncoder).
Send(body).
Err()
}
发送POST Form请求
func main() {
var body = struct {
Name string `form:"name"`
}{Name: "caster"}
// Content-Type: application/x-www-form-urlencoded
err := hasaki.
Post("http://localhost:8080" + "/sendForm").
SetEncoder(hasaki.FormEncoder).
Send(body).
Err()
}
发送字节流
package main
import (
"github.com/lxzan/hasaki"
"os"
)
func main() {
file, _ := os.Open("")
err := hasaki.
Put("http://localhost:8080" + "/upload").
SetHeader(hasaki.H{"Content-Type": hasaki.ContentTypeSTREAM}).
Send(file).
Err()
}
高级
设置代理
cli, err := hasaki.NewClient(hasaki.WithProxy("socks5://127.0.0.1:1080"))
统一的错误处理
package main
import (
"context"
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/lxzan/hasaki"
"github.com/pkg/errors"
"mime"
"net/http"
)
type BaseResult struct {
Code *int `json:"code"`
Message string `json:"message"`
}
var afterFunc = func(ctx context.Context, resp *http.Response) (context.Context, error) {
if resp.StatusCode != http.StatusOK {
return ctx, hasaki.ErrUnexpectedStatusCode
}
typ, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if typ != "application/json" {
return ctx, nil
}
rc, err := hasaki.NewReadCloser(resp.Body)
if err != nil {
return ctx, err
}
var result = BaseResult{}
if err := jsoniter.Unmarshal(rc.Bytes(), &result); err != nil {
return ctx, err
}
if result.Code == nil || *result.Code != 0 {
return ctx, errors.New(result.Message)
}
resp.Body = rc
return ctx, nil
}
func main() {
cli, _ := hasaki.NewClient(hasaki.WithAfter(afterFunc))
}
统计请求耗时
package main
import (
"context"
"fmt"
"github.com/lxzan/hasaki"
"net/http"
"time"
)
func main() {
cli, _ := hasaki.NewClient(
hasaki.WithBefore(func(ctx context.Context, request *http.Request) (context.Context, error) {
ctx = context.WithValue(ctx, "t0", time.Now())
return ctx, nil
}),
hasaki.WithAfter(func(ctx context.Context, response *http.Response) (context.Context, error) {
t0 := ctx.Value("t0").(time.Time)
fmt.Printf("cost = %dms\n", time.Since(t0).Milliseconds())
return ctx, nil
}),
)
cli.Get("https://api.github.com/users/%s", "lxzan").Send(nil)
}