golang: gout callback 使用示例

2019-10-23 09:32:52 +08:00
 guonaihong

很多时候我们的服务前面都有 proxy 代理中间件。这时候无论是用 http 当 rpc 调用,还是写个健康检查都要处理各种 http code 和各种 http body。

Callback

Callback 函数就是为了处理这种情况而开发。可以挂载多种处理函数,处理不同的 http 结果

func main() {
	go server() // 等会起测试服务
	time.Sleep(time.Millisecond * 500) //用时间做个等待同步

	r, str404 := Result{}, ""
	code := 0

	err := gout.GET(":8080").Code(&code).Callback(func(c *gout.Context) (err error) {

		switch c.Code {
		case 200:
			err = c.BindJSON(&r)
		case 404:
			err = c.BindBody(&str404)
		}
		return

	}).Do()

	if err != nil {
		fmt.Printf("err = %s\n", err)
		return
	}

	fmt.Printf("http code = %d, str404(%s), result(%v)\n", code, str404, r)
}

测试服务

用来模拟一定概率返回 404 html。和 200 json 结果

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/guonaihong/gout"
	"math/rand"
	"time"
)

type Result struct {
	Errmsg  string `json:"errmsg"`
	ErrCode int    `json:"errcode"`
}

// 模拟 nginx
func server() {
	router := gin.Default()

	router.GET("/", func(c *gin.Context) {

		rand.Seed(time.Now().UnixNano())
		x := rand.Intn(2) //生成 0-1 随机整数
		switch x {
		case 0: // 模拟 404 找不到资源
			c.String(404, "<html> not found </html>")
		case 1:
			c.JSON(200, Result{Errmsg: "ok"})
		}
	})

	router.Run()
}

gout

gout 是 go 实现的链式 http client
https://github.com/guonaihong/gout

1137 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/611965

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX