Skip to content

Commit

Permalink
Merge pull request #93 from yoyofx/dev
Browse files Browse the repository at this point in the history
1. Add Startup Env and flags
2. Add Http Server Path , such as /app/...
3. Add Config Path , Used read k8s ConfigMap
4.Add Demo docker image
  • Loading branch information
yoyofx authored Nov 12, 2020
2 parents 54f82ce + 9b09723 commit 82d67d1
Show file tree
Hide file tree
Showing 34 changed files with 2,013 additions and 351 deletions.
5 changes: 5 additions & 0 deletions .build/docker_build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# at root dir exec

docker build -f ./Examples/SimpleWeb/Dockerfile -t yoyofx/yoyogo:v-20201104-56b0d607160cac3954d21f545bcd644541667309 .

kubectl create configmap yoyogo-demo-test -n yoyogo --from-file=config_test.yml
45 changes: 37 additions & 8 deletions Abstractions/Configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/yoyofx/yoyogo/Utils"
"log"
"path"
)

type Configuration struct {
Expand All @@ -15,28 +17,43 @@ type Configuration struct {

func NewConfiguration(configContext *ConfigurationContext) *Configuration {
defaultConfig := viper.New()

flag.String("port", "", "application port")
flag.String("profile", configContext.profile, "application profile")
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
_ = defaultConfig.BindPFlags(pflag.CommandLine)
if configContext.enableEnv {
defaultConfig.AutomaticEnv()
defaultConfig.SetEnvPrefix("YYG")
}
if configContext.enableFlag {
flag.String("app", "", "application name")
flag.String("port", "", "application port")
flag.String("profile", configContext.profile, "application profile")
flag.String("conf", ".", "config dir")
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
_ = defaultConfig.BindPFlags(pflag.CommandLine)
}

if pf := defaultConfig.GetString("profile"); pf != "" {
configContext.profile = pf
}

if cf := defaultConfig.GetString("conf"); cf != "" {
configContext.configDir = cf
}

configName := configContext.configName + "_" + configContext.profile
exists, _ := Utils.PathExists("./" + configName + "." + configContext.configType)
configFilePath := path.Join(configContext.configDir, configName+"."+configContext.configType)
exists, _ := Utils.PathExists(configFilePath)
if !exists {
configName = configContext.configName
}

defaultConfig.AddConfigPath(".")
defaultConfig.AddConfigPath(configContext.configDir)
defaultConfig.SetConfigName(configName)
defaultConfig.SetConfigType(configContext.configType)
if err := defaultConfig.ReadInConfig(); err != nil {
panic(err)
return nil
}
log.Println(configFilePath)

return &Configuration{
context: configContext,
Expand All @@ -48,6 +65,14 @@ func (c *Configuration) Get(name string) interface{} {
return c.config.Get(name)
}

func (c *Configuration) GetString(name string) string {
return c.config.GetString(name)
}

func (c *Configuration) GetInt(name string) int {
return c.config.GetInt(name)
}

func (c *Configuration) GetSection(name string) IConfiguration {
section := c.config.Sub(name)

Expand All @@ -67,3 +92,7 @@ func (c *Configuration) Unmarshal(obj interface{}) {
func (c *Configuration) GetProfile() string {
return c.context.profile
}

func (c *Configuration) GetConfDir() string {
return c.context.configDir
}
2 changes: 2 additions & 0 deletions Abstractions/ConfigurationBuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import "github.com/yoyofx/yoyogo/Abstractions/Env"
type ConfigurationContext struct {
enableFlag bool
enableEnv bool
configDir string
configType string
configName string
profile string
Expand Down Expand Up @@ -51,5 +52,6 @@ func (builder *ConfigurationBuilder) BuildEnv(env string) *Configuration {

func (builder *ConfigurationBuilder) Build() *Configuration {
builder.context.profile = Env.Dev
builder.context.enableFlag = true
return NewConfiguration(builder.context)
}
8 changes: 8 additions & 0 deletions Abstractions/HostBuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ func (host *HostBuilder) UseConfiguration(configuration IConfiguration) *HostBui
if portInterface != nil && portInterface.(string) != "" {
config.Server.Address = ":" + portInterface.(string)
}
appName := configuration.GetString("app")
if appName != "" {
config.Name = appName
}
host.Context.HostConfiguration = config
}
return host
Expand Down Expand Up @@ -98,6 +102,10 @@ func buildingHostEnvironmentSetting(context *HostBuildContext) {
hostEnv := context.HostingEnvironment
hostEnv.Version = YoyoGo.Version
hostEnv.Addr = DetectAddress("")
hostEnv.MetaData = make(map[string]string)
hostEnv.MetaData["config.path"] = context.Configuration.GetConfDir()
hostEnv.MetaData["server.path"] = context.Configuration.GetString("yoyogo.application.server.path")
hostEnv.MetaData["mvc.template"] = context.Configuration.GetString("yoyogo.application.server.mvc.template")
config := context.HostConfiguration
if config != nil {
hostEnv.ApplicationName = config.Name
Expand Down
3 changes: 3 additions & 0 deletions Abstractions/IConfiguration.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package Abstractions

type IConfiguration interface {
Get(name string) interface{}
GetString(name string) string
GetInt(name string) int
GetSection(name string) IConfiguration
Unmarshal(interface{})
GetProfile() string
GetConfDir() string
}
8 changes: 5 additions & 3 deletions Abstractions/IServiceHost.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,11 @@ func PrintLogo(l XLog.ILogger, env *Context.HostEnvironment) {
l.Debug("listening on port : %s", ConsoleColors.Blue(env.Port))
l.Debug("application running pid : %s", ConsoleColors.Blue(strconv.Itoa(env.PID)))
l.Debug("application name : %s", ConsoleColors.Blue(env.ApplicationName))
l.Debug("application environment : %s", ConsoleColors.Blue(env.Profile))
l.Debug("application exec path : %s", ConsoleColors.Yellow(Utils.GetCurrentDirectory()))
l.Debug("running in %s mode , change (Dev,Test,Prod) mode by HostBuilder.SetEnvironment .", ConsoleColors.Blue(env.Profile))
l.Debug(ConsoleColors.Green("Starting HTTP server..."))
l.Debug("application config path : %s", ConsoleColors.Yellow(env.MetaData["config.path"]))
l.Debug("application environment : %s", ConsoleColors.Yellow(ConsoleColors.Blue(env.Profile)))
l.Debug("running in %s mode , change (Dev,Test,Prod) mode by HostBuilder.SetEnvironment .", ConsoleColors.Red(env.Profile))
l.Debug(ConsoleColors.Green("Starting server..."))
l.Debug("server setting map : %v", env.MetaData)

}
16 changes: 11 additions & 5 deletions Examples/GrafanaAlertWebHook/WechatRequests/QiyeWechat.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,27 @@ func SendTxtMessage(request GrafanaAlertRequest, config Abstractions.IConfigurat
tag := request.GetTag()
logger := XLog.GetXLogger("wechat")
js, _ := json.Marshal(request)
logger.Info(string(js))
logger.Info("Request json: %s", string(js))
if tag == "" {
logger.Info("no send")
return ""
}
sendUrl := config.Get("alert.webhook_url").(string)
sendUrl := config.Get(fmt.Sprintf("alert.%s.webhook_url", tag)).(string)
linkUrl := config.Get(fmt.Sprintf("alert.%s.link_url", tag)).(string)
logger.Info("request tag:%s", tag)
logger.Info(sendUrl)
logger.Info(linkUrl)

var message *MarkdownMessage
if request.State == "alerting" && len(request.EvalMatches) > 0 {
message = &MarkdownMessage{
Markdown: struct {
Content string `json:"content" gorm:"column:content"`
}{
Content: request.RuleName + ",请相关同事注意。\n" +
" > [报警次数]:<font color=\"warning\">" + request.GetMetricValue() + "次</font>" + "\n" +
" > [报警明细](" + linkUrl + ")\n",
Content: "## " + request.RuleName + ",请相关同事注意。\n" +
" > [报警信息] : " + request.Message + "\n" +
" > [报警次数] : <font color=\"warning\">" + request.GetMetricValue() + "次</font>" + "\n" +
" > [报警明细] : (" + linkUrl + ")\n",
},
Msgtype: "markdown",
}
Expand All @@ -55,5 +60,6 @@ func SendTxtMessage(request GrafanaAlertRequest, config Abstractions.IConfigurat
msgStr := string(msg)
logger.Info("send message:%s", msgStr)

//return sendUrl + msgStr
return postWechatMessage(sendUrl, msgStr)
}
3 changes: 2 additions & 1 deletion Examples/GrafanaAlertWebHook/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ yoyogo:

# alert通过 tag识别节点值
alert:
webhook_url: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=014f19d9-929e-4349-9b0f-ee57d868da9e
jishi:
webhook_url: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=014f19d9-929e-4349-9b0f-ee57d868da9e
link_url: http://jcenter-main.easypass.cn/jiankong/d/trpHG7FGk/che-hou-ye-wu-ri-zhi-cha-xun?orgId=1&from=now-1h&to=now&var-app=jishi*&var-level=error&var-host=All&var-msg=*
znbk:
webhook_url: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2319bfd0-9bb4-4cb6-8598-a2f191fc8e81
link_url: http://jcenter-main.easypass.cn/jiankong/d/trpHG7FGk/che-hou-ye-wu-ri-zhi-cha-xun?orgId=1&from=now-1h&to=now&var-app=zhineng*&var-level=error&var-host=All&var-msg=*
25 changes: 0 additions & 25 deletions Examples/GrafanaAlertWebHook/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,4 @@ func PostAlert(ctx *Context.HttpContext) {
ctx.JSON(200, Context.H{
"Message": WechatRequests.SendTxtMessage(request, config),
})

//var message WechatRequests.MarkdownMessage
//if request.State == "alerting" && len(request.EvalMatches) > 0 {
// message = WechatRequests.MarkdownMessage{
// Markdown: struct {
// Content string `json:"content" gorm:"column:content"`
// }{
// Content: request.RuleName + ",请相关同事注意。\n" +
// " > [报警次数]:<font color=\"warning\">" + strconv.Itoa(request.EvalMatches[0].Value) + "次</font>" + "\n" +
// " > [报警明细](http://jcenter-main.easypass.cn/jiankong/d/trpHG7FGk/che-hou-ye-wu-ri-zhi-cha-xun?orgId=1&from=now-1h&to=now&var-app=jishi*&var-level=error&var-host=All&var-msg=*)\n",
// },
// Msgtype: "markdown",
// }
// //msg, _ := json.Marshal(message)
// //sendUrl := "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=efaebe93-7b21-4bc3-888f-260744f397ac"
// //ctx.JSON(200, Context.H{
// // "Message": postWechatMessage(sendUrl,string(msg)),
// //})
// ctx.JSON(200, message)
//}
//msg, _ := json.Marshal(message)
//
//ctx.JSON(200,Context.H{
// "Message":postWechatMessage(string(msg)) ,
//})
}
2 changes: 2 additions & 0 deletions Examples/GrafanaAlertWebHook/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"github.com/yoyofx/yoyogo/Abstractions"
"github.com/yoyofx/yoyogo/WebFramework"
"github.com/yoyofx/yoyogo/WebFramework/Endpoints"
"github.com/yoyofx/yoyogo/WebFramework/Router"
)

Expand All @@ -14,6 +15,7 @@ func main() {
Configure(func(app *YoyoGo.WebApplicationBuilder) {
app.UseEndpoints(func(router Router.IRouterBuilder) {
router.POST("/alert", PostAlert)
Endpoints.UsePrometheus(router)
})
}).Build().Run()
}
23 changes: 0 additions & 23 deletions Examples/SimpleWeb/DOCKERFILE

This file was deleted.

48 changes: 48 additions & 0 deletions Examples/SimpleWeb/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
FROM golang:latest AS builder

# 为我们的镜像设置必要的环境变量
ENV GO111MODULE=on \
CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64 \
GOPROXY=https://goproxy.cn,direct

# 移动到工作目录:/build
WORKDIR /build

# 将代码复制到容器中
COPY . .
WORKDIR /build/Examples/SimpleWeb
RUN ls
# 将我们的代码编译成二进制可执行文件 app
RUN go build -o app .

###################
# 接下来创建一个小镜像
###################
FROM alpine

#更新Alpine的软件源为国内源,提高下载速度
RUN echo "https://mirror.tuna.tsinghua.edu.cn/alpine/v3.4/main/" > /etc/apk/repositories

RUN apk update \
&& apk upgrade \
&& apk add --no-cache bash \
bash-doc \
bash-completion \
&& rm -rf /var/cache/apk/* \
&& /bin/bash
# 设置时区为上海
RUN apk -U add tzdata && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone \
&& apk del tzdata

# 从builder镜像中把/dist/app 拷贝到当前目录
COPY --from=builder /build/Examples/SimpleWeb/app /
COPY --from=builder /build/Examples/SimpleWeb/config_dev.yml /
COPY --from=builder /build/Examples/SimpleWeb/config_prod.yml /

# RUN chmod +x /app

# 需要运行的命令
ENTRYPOINT ["/app"]
13 changes: 8 additions & 5 deletions Examples/SimpleWeb/config_dev.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
yoyogo:
application:
name: demo_dev
name: yoyogo_demo_dev
metadata: "develop"
server:
type: "fasthttp"
address: ":8082"
address: ":8080"
path: "app"
max_request_size: 2096157
mvc:
template: "/v1/{controller}/{action}"
static:
patten: "/"
webroot: "./Static"
Expand All @@ -17,7 +20,7 @@ yoyogo:
secret: "12391JdeOW^%$#@"
prefix: "Bearer"
expires: 3
enable: true
enable: false
skip_path: [
"/info",
"/v1/user/GetInfo",
Expand All @@ -34,8 +37,8 @@ yoyogo:
discovery:
type: "nacos"
metadata:
url: "localhost"
port: 8848
url: "120.53.133.30"
port: 80
namespace: "public"
group_name: ""
# clusters: [""]
Expand Down
Loading

0 comments on commit 82d67d1

Please sign in to comment.