go-file-serve/routes/routes.go

75 lines
1.4 KiB
Go
Raw Normal View History

2019-02-25 14:56:48 +00:00
package routes
import (
2019-02-26 09:42:56 +00:00
"html/template"
2019-02-26 09:02:43 +00:00
"io/ioutil"
"log"
2019-02-25 15:16:16 +00:00
"net/http"
2019-02-26 09:02:43 +00:00
"path"
2019-02-26 09:42:56 +00:00
"regexp"
2019-02-25 15:16:16 +00:00
"git.trj.tw/golang/go-file-serve/module/context"
"git.trj.tw/golang/go-file-serve/routes/api"
"github.com/gin-gonic/gin"
2019-02-25 14:56:48 +00:00
)
// NewEngine -
2019-02-25 15:16:16 +00:00
func NewEngine() *gin.Engine {
2019-02-25 14:56:48 +00:00
engine := gin.New()
engine.Use(gin.Logger())
engine.Use(gin.Recovery())
return engine
}
// SetRoutes -
func SetRoutes(r *gin.Engine) {
2019-02-26 09:42:56 +00:00
r.SetFuncMap(template.FuncMap{
"parsePath": func(p string) string {
regex := regexp.MustCompile("^/")
p = regex.ReplaceAllString(p, "")
regex = regexp.MustCompile("/$")
p = regex.ReplaceAllString(p, "")
return p
},
})
2019-02-26 09:02:43 +00:00
tmpls := make([]string, 0)
files, err := ioutil.ReadDir("./templates")
if err != nil {
log.Fatal(err)
}
for _, v := range files {
if !v.IsDir() {
tmpls = append(tmpls, path.Join("./templates", v.Name()))
}
}
r.LoadHTMLFiles(tmpls...)
2019-02-25 15:16:16 +00:00
r.GET("/", func(c *gin.Context) {
2019-02-25 14:56:48 +00:00
c.JSON(http.StatusOK, gin.H{
"message": "success",
})
})
2019-02-25 15:16:16 +00:00
2019-02-26 09:02:43 +00:00
r.GET("/html", func(c *gin.Context) {
c.HTML(200, "content.tmpl", gin.H{"title": "test title"})
})
2019-02-25 15:16:16 +00:00
apiGroup := r.Group("/api")
{
apiGroup.GET("/files", context.PatchContext(api.GetFileList))
}
viewGroup := r.Group("/v")
{
viewGroup.GET("*path", context.PatchContext(FSList))
}
dlGroup := r.Group("/dl")
{
dlGroup.GET("*path", func(c *gin.Context) {
c.JSON(200, gin.H{})
})
}
2019-02-25 14:56:48 +00:00
}