GithubHelp home page GithubHelp logo

hasaki's Introduction

Hasaki

http request library for golang

Build Status OSCS Status

  • 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)
}

hasaki's People

Contributors

lxzan avatar masterbool avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.