GoSage
介绍
go-sage框架,目前自用
参考示例
参考示例统一放在 ./examples 下
Documents
App
统一管理各类服务资源的处理器
启用多个服务
func main() {
logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))
//log
logger := v1log.NewLog("exampleApp", logPath, nil)
//创建一个http server
server1 := getHttpServer(logger)
app, err := v1.NewApp(
"exampleApp",
v1.WithAppOpsLog(logger), //放入logger
v1.WithAppOpsServer(server1), //放入一个 server
v1.WithAppOpsServer(server2),
)
if err != nil {
logger.Fatal(fmt.Sprintf("new app error:%s", err))
return
}
err = app.Run()
if err != nil {
logger.Fatal("app running error: " + err.Error())
}
}
添加logger
app, err := v1.NewApp(
"exampleApp",
v1.WithAppOpsLog(logger), #初始化时设置logger
v1.WithAppOpsStopTimeout(time.Second*5),
v1.WithAppOpsServer(server1),
v1.WithAppOpsServer(server2),
)
#也可单独设置logger
app.AddLogger(logger)
err = app.Run()
if err != nil {
logger.Fatal("app running error: " + err.Error())
}
一键暂停服务
app可调用 Stop 方法直接暂停所有服务
go func() {
time.Sleep(time.Second * 3)
logger.Info("stop server")
app.Stop()
}()
err = app.Run()
if err != nil {
logger.Fatal("app running error: " + err.Error())
}
并且任意一个服务停止也会触发整体服务暂停
go func() {
time.Sleep(time.Second * 10)
logger.Info("stop server")
server1.Stop()
}()
err = app.Run()
if err != nil {
logger.Fatal("app running error: " + err.Error())
}
支持自定义服务
使用包里提供的 WithAppOpsServer(server2) 方法,只要提供的服务符合以下接口就可支持添加
type IServer interface {
Name() string
Run() error
Stop() error
}
设置 StopTimeout
设置了 StopTimeout 后,如果服务在超时时间外还未暂停,会强制结束
app, err := v1.NewApp(
"exampleApp",
v1.WithAppOpsLog(logger),
v1.WithAppOpsStopTimeout(time.Second*5), #初始化时设置
v1.WithAppOpsServer(server1),
v1.WithAppOpsServer(server2),
)
HttpServer
httpServer负责 http服务器 的启动管理
直接启动
func main() {
name := "example"
logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))
logger := v1log.NewZapLog(name, logPath, nil)
httpServer, err := v1http.NewHttpServer("", ":8080")
if err != nil {
logger.Error("run http server error:%s" + err.Error())
return
}
//添加logger
httpServer.AddLogger(logger)
logger.Fatal(httpServer.Run().Error())
}
注册路由
路由方法需要是以下的类型
func(ctx *Ctx)
GET/POST/DELETE/OPTION/PUT 路由
//注册简单的路由
httpServer.RouteGet("/v1/users", api.Users, nil)
httpServer.RoutePost("/v1/exception", api.Exception, nil)
httpServer.RouteOptions("/v1/exception", api.Exception, nil)
httpServer.RouteDelete("/v1/exception", api.Exception, nil)
httpServer.RoutePut("/v1/exception", api.Exception, nil)
静态文件请求
#
httpServer.RouteFiles("/static", http.Dir("public"))
请求处理
//直接使用 write 返回
func (h *ApiHandler) Index(ctx *v1http.Ctx) {
ctx.Write([]byte("Hello World"))
}
//使用内置的返回格式
func (h *ApiHandler) Users(ctx *v1http.Ctx) {
users := []map[string]interface{}{
{"uid": 1, "username": "jack"},
{"uid": 2, "username": "lucy"},
}
ctx.Data(users)
ctx.Msg("success")
ctx.Response()
}
#自定义返回状态
func (h *ApiHandler) Exception(ctx *v1http.Ctx) {
ctx.WriteHeader(500)
ctx.Response()
}
中间件(待完善)