V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
guonaihong
V2EX  ›  程序员

golang: gout callback 使用示例

  •  
  •   guonaihong ·
    guonaihong · 2019-10-23 09:32:52 +08:00 · 1131 次点击
    这是一个创建于 1639 天前的主题,其中的信息可能已经有所发展或是发生改变。

    很多时候我们的服务前面都有 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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3536 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:45 · PVG 18:45 · LAX 03:45 · JFK 06:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.