From c67e110c7e17ef15c5fce18cf1d7fc2439cc9ab8 Mon Sep 17 00:00:00 2001 From: Jay Date: Tue, 26 Feb 2019 17:42:56 +0800 Subject: [PATCH] add list template --- module/context/context.go | 6 ++++++ routes/files.go | 31 ++++++++++++++++++++++++------- routes/routes.go | 13 +++++++++++++ 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/module/context/context.go b/module/context/context.go index bc82dcd..0ecba5e 100644 --- a/module/context/context.go +++ b/module/context/context.go @@ -48,6 +48,12 @@ func (p *Context) BindData(i interface{}) error { return p.ShouldBindWith(i, b) } +// HTML - +func (p *Context) HTML(tmpl string, data interface{}) { + p.Context.HTML(http.StatusOK, tmpl, data) + p.Abort() +} + // Success - func (p *Context) Success(res ...interface{}) { var resBody interface{} diff --git a/routes/files.go b/routes/files.go index ca4ecff..753aafd 100644 --- a/routes/files.go +++ b/routes/files.go @@ -1,17 +1,21 @@ package routes import ( + "fmt" "io/ioutil" "path" "regexp" + "time" "git.trj.tw/golang/go-file-serve/module/config" "git.trj.tw/golang/go-file-serve/module/context" ) type responseFS struct { - Name string `json:"name"` - Path string `json:"path"` + Name string `json:"name"` + Path string `json:"path"` + Size int64 `json:"size"` + Mtime time.Time `json:"mtime"` } // FSList - @@ -39,8 +43,10 @@ func FSList(c *context.Context) { for _, v := range info { f := responseFS{ - Name: v.Name(), - Path: path.Join(p, v.Name()), + Name: v.Name(), + Path: path.Join(p, v.Name()), + Size: v.Size(), + Mtime: v.ModTime(), } if v.IsDir() { f.Name += "/" @@ -50,8 +56,19 @@ func FSList(c *context.Context) { } } - c.Success(map[string]interface{}{ - "directory": dirs, - "file": files, + list := make([]responseFS, 0, len(dirs)+len(files)) + list = append(list, dirs...) + list = append(list, files...) + dirs = nil + files = nil + + c.HTML("list.tmpl", map[string]interface{}{ + "title": fmt.Sprintf("Path: /%s", p), + "path": fmt.Sprintf("/%s", p), + "list": list, }) + // c.Success(map[string]interface{}{ + // "directory": dirs, + // "file": files, + // }) } diff --git a/routes/routes.go b/routes/routes.go index ccf86cf..050ea2f 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -1,10 +1,12 @@ package routes import ( + "html/template" "io/ioutil" "log" "net/http" "path" + "regexp" "git.trj.tw/golang/go-file-serve/module/context" "git.trj.tw/golang/go-file-serve/routes/api" @@ -22,6 +24,17 @@ func NewEngine() *gin.Engine { // SetRoutes - func SetRoutes(r *gin.Engine) { + + 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 + }, + }) + tmpls := make([]string, 0) files, err := ioutil.ReadDir("./templates") if err != nil {