Skip to content

Commit

Permalink
1.框架启动方法优化,2.redislock新增tryLock方法,3.schedule新增状态查询支持,4.其他代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
keepchen committed Jan 24, 2024
1 parent 68ae848 commit 321355c
Show file tree
Hide file tree
Showing 15 changed files with 795 additions and 292 deletions.
2 changes: 1 addition & 1 deletion constants/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const (
var initErrorCodeMsgMap = map[CodeType]string{
ErrNone: "SUCCESS",
ErrRequestParamsInvalid: "Bad request parameters",
ErrAuthorizationTokenInvalid: "Token invalid",
ErrAuthorizationTokenInvalid: "Authorization token invalid",
ErrInternalServerError: "Internal server error",
}

Expand Down
34 changes: 26 additions & 8 deletions examples/pkg/app/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ import (
"sync"
"time"

"github.com/keepchen/go-sail/v3/examples/pkg/app/user/http/routes"

"github.com/keepchen/go-sail/v3/sail/config"
"github.com/keepchen/go-sail/v3/schedule"

"github.com/keepchen/go-sail/v3/lib/logger"

"github.com/keepchen/go-sail/v3/examples/pkg/app/user/http/routes"

"github.com/keepchen/go-sail/v3/constants"

"github.com/keepchen/go-sail/v3/http/api"
Expand Down Expand Up @@ -83,24 +83,42 @@ func StartServer(wg *sync.WaitGroup) {
ErrNoneCodeMsg: "SUCCEED",
ForceHttpCode200: true,
}
before = func() {
beforeFunc = func() {
fmt.Println("call user function [before] to do something...")
}
after = func() {
afterFunc = func() {
fmt.Println("call user function [after] to do something...")
cancel0 := schedule.Job("print now datetime", func() {
job0 := "print now datetime"
cancel0 := schedule.Job(job0, func() {
fmt.Println("now: ", utils.FormatDate(time.Now(), utils.YYYY_MM_DD_HH_MM_SS_EN))
}).RunAt(schedule.EveryMinute)
time.AfterFunc(time.Minute*3, cancel0)

cancel1 := schedule.Job("print hello", func() {
job1 := "print hello"
cancel1 := schedule.Job(job1, func() {
time.Sleep(time.Second * 10)
fmt.Println(utils.FormatDate(time.Now(), utils.YYYY_MM_DD_HH_MM_SS_EN), "hello")
}).EverySecond()
time.AfterFunc(time.Second*5, cancel1)
time.AfterFunc(time.Second*33, cancel1)

ticker := time.NewTicker(time.Second)
times := 0
LOOP:
for range ticker.C {
times++
fmt.Printf("job: {%s} is running: %t | job: {%s} is running: %t\n",
job0, schedule.JobIsRunning(job0), job1, schedule.JobIsRunning(job1))
if times > 50 {
break LOOP
}
}
}
)

sail.WakeupHttp("go-sail", conf, apiOption).Launch(routes.RegisterRoutes, before, after)
//直接启动
//sail.WakeupHttp("go-sail", conf).Launch(routes.RegisterRoutes)
//挂载处理方法后启动
sail.WakeupHttp("go-sail", conf).SetupApiOption(apiOption).Hook(routes.RegisterRoutes, beforeFunc, afterFunc).Launch()
}

// RegisterServicesToNacos 将服务注册到注册中心
Expand Down
26 changes: 18 additions & 8 deletions http/api/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,24 @@ import (
"github.com/keepchen/go-sail/v3/http/pojo/dto"
)

type Emitter interface {
Builder(code constants.ICodeType, resp dto.IResponse, message ...string) Emitter
Assemble(code constants.ICodeType, resp dto.IResponse, message ...string) Emitter
Status(httpCode int) Emitter
SendWithCode(httpCode int)
Send()
}

type API struct {
engine *gin.Context
httpCode int
data interface{}
}

func New(c *gin.Context) API {
return API{
var _ Emitter = &API{}

func New(c *gin.Context) Emitter {
return &API{
engine: c,
}
}
Expand All @@ -31,21 +41,21 @@ func New(c *gin.Context) API {
// Response(c).Builder(...).Send()
//
// New 方法的语法糖
func Response(c *gin.Context) API {
func Response(c *gin.Context) Emitter {
return New(c)
}

// Builder 组装返回数据
//
// Assemble 方法的语法糖
func (a API) Builder(code constants.ICodeType, resp dto.IResponse, message ...string) API {
func (a *API) Builder(code constants.ICodeType, resp dto.IResponse, message ...string) Emitter {
return a.Assemble(code, resp, message...)
}

// Assemble 组装返回数据
//
// 该方法会根据传递的code码自动设置http状态、描述信息、当前系统毫秒时间戳以及请求id(需要在路由配置中调用middleware.Before中间件)
func (a API) Assemble(code constants.ICodeType, resp dto.IResponse, message ...string) API {
func (a *API) Assemble(code constants.ICodeType, resp dto.IResponse, message ...string) Emitter {
var (
body dto.Base
requestId string
Expand Down Expand Up @@ -124,18 +134,18 @@ func (a API) Assemble(code constants.ICodeType, resp dto.IResponse, message ...s
// Status 指定http状态码
//
// 该方法会覆盖 Assemble 解析的http状态码值
func (a API) Status(httpCode int) API {
func (a *API) Status(httpCode int) Emitter {
a.httpCode = httpCode

return a
}

// SendWithCode 以指定http状态码响应请求
func (a API) SendWithCode(httpCode int) {
func (a *API) SendWithCode(httpCode int) {
a.engine.AbortWithStatusJSON(httpCode, a.data)
}

// Send 响应请求
func (a API) Send() {
func (a *API) Send() {
a.SendWithCode(a.httpCode)
}
6 changes: 3 additions & 3 deletions sail/components.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ func GetNats() *natsLib.Conn {
}

// GetLogger 获取日志实例
func GetLogger(modules ...string) *zap.Logger {
return logger.GetLogger(modules...)
func GetLogger(module ...string) *zap.Logger {
return logger.GetLogger(module...)
}

// Response http响应组件
func Response(c *gin.Context) api.API {
func Response(c *gin.Context) api.Emitter {
return api.New(c)
}

Expand Down
24 changes: 12 additions & 12 deletions sail/config/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ import (
func PrintTemplateConfig(format string, writeToFile ...string) {
var (
abort bool
configStr []byte
config = Config{}
cfgStr []byte
cfg = Config{}
formatList = [...]string{"json", "yaml", "toml"}
)
switch format {
case formatList[0]:
configStr, _ = json.MarshalIndent(&config, "", " ")
cfgStr, _ = json.MarshalIndent(&cfg, "", " ")
case formatList[1]:
configStr, _ = yaml.Marshal(&config)
cfgStr, _ = yaml.Marshal(&cfg)
case formatList[2]:
configStr, _ = toml.Marshal(&config)
cfgStr, _ = toml.Marshal(&cfg)
default:
fmt.Printf("[GO-SAIL] <Config> dump config by using unknown format: %s\n", format)
abort = true
Expand All @@ -39,13 +39,13 @@ func PrintTemplateConfig(format string, writeToFile ...string) {
}

if len(writeToFile) > 0 {
err := utils.FilePutContents(configStr, writeToFile[0])
err := utils.FilePutContents(cfgStr, writeToFile[0])
if err != nil {
fmt.Printf("[GO-SAIL] <Config> dump config to file {%s} error: %s\n", writeToFile[0], err.Error())
}
} else {
fmt.Printf("[GO-SAIL] <Config> dump config (%s) to stdout:\n", format)
fmt.Println(string(configStr))
fmt.Println(string(cfgStr))
}
}

Expand All @@ -57,21 +57,21 @@ func PrintTemplateConfig(format string, writeToFile ...string) {
func ParseConfigFromBytes(format string, source []byte) (*Config, error) {
var (
formatList = [...]string{"json", "yaml", "toml"}
conf Config
cfg Config
err error
)

switch format {
case formatList[0]:
err = json.Unmarshal(source, &conf)
err = json.Unmarshal(source, &cfg)
case formatList[1]:
err = yaml.Unmarshal(source, &conf)
err = yaml.Unmarshal(source, &cfg)
case formatList[2]:
err = toml.Unmarshal(source, &conf)
err = toml.Unmarshal(source, &cfg)
default:
fmt.Printf("[GO-SAIL] <Config> dump config by using unknown format: %s\n", format)
err = fmt.Errorf("[GO-SAIL] <Config> dump config by using unknown format: %s\n", format)
}

return &conf, err
return &cfg, err
}
4 changes: 2 additions & 2 deletions sail/httpserver/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
)

// RunPrometheusServer 启动prometheus指标收集服务
// RunPrometheusServerOnDebugMode 启动prometheus指标收集服务
//
// 当配置文件指明启用时才会启动
func RunPrometheusServer(conf config.PrometheusConf) {
func RunPrometheusServerOnDebugMode(conf config.PrometheusConf) {
if !conf.Enable {
return
}
Expand Down
4 changes: 2 additions & 2 deletions sail/httpserver/swagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import (
ginSwagger "github.com/swaggo/gin-swagger"
)

// RunSwaggerServer 启动swagger文档服务
// RunSwaggerServerOnDebugMode 启动swagger文档服务
//
// 当配置文件指明启用时才会启动
func RunSwaggerServer(conf config.SwaggerConf, ginEngine *gin.Engine) {
func RunSwaggerServerOnDebugMode(conf config.SwaggerConf, ginEngine *gin.Engine) {
if !conf.Enable {
//如果不是调试模式就不注册swagger路由
return
Expand Down
Loading

0 comments on commit 321355c

Please sign in to comment.