You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

77 lines
1.9 KiB

package main
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/radovskyb/watcher"
"github.com/spf13/cobra"
)
func serveCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "serve",
Short: "run a serve locally",
Run: func(cmd *cobra.Command, args []string) {
w := watcher.New()
w.SetMaxEvents(1)
w.FilterOps(watcher.Rename, watcher.Move, watcher.Write, watcher.Create)
if err := w.AddRecursive("./data"); err != nil {
sfault("watch directory data failed: %v", err)
}
if err := w.AddRecursive("./posts"); err != nil {
sfault("watch directory posts failed: %v", err)
}
if err := w.AddRecursive("./pages"); err != nil {
sfault("watch directory pages failed: %v", err)
}
if err := w.AddRecursive("./themes"); err != nil {
sfault("watch directory pages failed: %v", err)
}
if err := w.Add("config.yaml"); err != nil {
sfault("watch file failed: %v", err)
}
// start http server
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.Static("/", "./dist")
server := http.Server{
Addr: ":8666",
Handler: router,
}
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
sfault("listen server failed: %v", err)
}
}()
go func() {
for {
select {
case event := <-w.Event:
// 文件变更 更新文件
if err := deployCmd().Execute(); err != nil {
sfault("re generate website failed: %v", err)
}
sout("file change: %v", event.String())
case err := <-w.Error:
sfault("watch file failed: %v", err)
case <-w.Closed:
return
}
}
}()
// 先生成一次
if err := deployCmd().Execute(); err != nil {
sfault("generate website failed: %v", err)
}
// 五秒一次
sout("http://127.0.0.1:8666")
if err := w.Start(time.Second * 5); err != nil {
sfault("watch file failed: %v", err)
}
},
}
return cmd
}