Skip to content

Commit

Permalink
[feature] 新增spider健康检查
Browse files Browse the repository at this point in the history
  • Loading branch information
runs committed Jan 1, 2023
1 parent 8a2d3de commit 82dc98e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
16 changes: 15 additions & 1 deletion cmd/spider/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"

"git.vtb.link/eoefans/internal/app/spider"
"git.vtb.link/eoefans/internal/app/spider/health"
"git.vtb.link/eoefans/internal/app/spider/video_analysis"
"git.vtb.link/eoefans/internal/launcher"
"git.vtb.link/eoefans/internal/pkg/bilibili"
Expand All @@ -22,11 +23,12 @@ func newSpider() fx.Option {
fx.Provide(spider.NewVideo),
fx.Provide(spider.NewUpdate),
fx.Provide(bilibili.NewSDK),
fx.Provide(health.NewCheckServer),
fx.Invoke(lc),
)
}

func lc(lifecycle fx.Lifecycle, spiderVideo *spider.Video, spiderUpdate *spider.Update, shutdown fx.Shutdowner) {
func lc(lifecycle fx.Lifecycle, spiderVideo *spider.Video, spiderUpdate *spider.Update, checkServer *health.CheckServer, shutdown fx.Shutdowner) {
lifecycle.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
return spiderVideo.Run(ctx)
Expand All @@ -50,4 +52,16 @@ func lc(lifecycle fx.Lifecycle, spiderVideo *spider.Video, spiderUpdate *spider.
return shutdown.Shutdown()
},
})

lifecycle.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
return checkServer.Run(ctx)
},
OnStop: func(ctx context.Context) error {
if err := checkServer.Stop(ctx); err != nil {
return err
}
return shutdown.Shutdown()
},
})
}
34 changes: 34 additions & 0 deletions internal/app/spider/health/httpserver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package health

import (
"context"
"fmt"
"net/http"
"time"
)

type CheckServer struct {
server *http.Server
}

func NewCheckServer() *CheckServer {
http.HandleFunc("/check", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(fmt.Sprintf(`{"code":0, "message": "ok", "data": {"now_time": %s}}`, time.Now().Format(time.RFC3339))))
})

return &CheckServer{
server: &http.Server{
Addr: ":9266",
Handler: http.DefaultServeMux,
},
}
}

func (check *CheckServer) Run(ctx context.Context) error {
return check.server.ListenAndServe()
}

func (check *CheckServer) Stop(ctx context.Context) error {
return check.server.Shutdown(ctx)
}

0 comments on commit 82dc98e

Please sign in to comment.