本书未发布

8.10. 读取http远程配置

未匹配的标注
package main

import (
    "encoding/json"
    "net/http"
    "strings"

    "github.com/eudore/eudore"
)

func main() {
    app := eudore.NewApp()
    // 修改第一个解析函数为readHttp解析http请求
    app.ParseOption(func([]eudore.ConfigParseFunc) []eudore.ConfigParseFunc {
        return []eudore.ConfigParseFunc{readHttp, eudore.ConfigParseArgs, eudore.ConfigParseEnvs, eudore.ConfigParseMods, eudore.ConfigParseWorkdir, eudore.ConfigParseHelp}
    })
    app.Set("config", []string{"http://127.0.0.1:8089/xxx", "http://127.0.0.1:8088/xxx"})
    app.Set("help", true)

    go func(app2 *eudore.App) {
        app := eudore.NewApp()
        app.AnyFunc("/*", func(ctx eudore.Context) {
            ctx.WriteJSON(map[string]interface{}{
                "route": "/*",
                "name":  "eudore",
            })
        })
        app.Listen(":8088")

        app2.Options(app.Parse())
        app2.CancelFunc()
        app.CancelFunc()
        app.Run()
    }(app)

    app.Run()
}

// 自定义一个解析http请求的配置解析函数
func readHttp(c eudore.Config) error {
    for _, path := range eudore.GetStrings(c.Get("config")) {
        if !strings.HasPrefix(path, "http://") && !strings.HasPrefix(path, "https://") {
            continue
        }
        resp, err := http.Get(path)
        if err == nil {
            err = json.NewDecoder(resp.Body).Decode(c)
            resp.Body.Close()
        }
        if err == nil {
            c.Set("print", "read http succes json config by "+path)
            return nil
        }
        c.Set("print", "read http fatal "+path+" error: "+err.Error())
    }
    return nil
}

反馈和交流请加群组:QQ群373278915

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~