filebrowser/hugo.go

88 lines
2.0 KiB
Go
Raw Normal View History

2015-09-13 19:37:20 +00:00
//go:generate go-bindata -pkg assets -o assets/assets.go static/css/ static/js/ templates/
2015-09-13 11:14:18 +00:00
2015-09-12 08:52:41 +00:00
package hugo
import (
2015-09-13 19:37:20 +00:00
"mime"
2015-09-12 08:52:41 +00:00
"net/http"
2015-09-13 19:37:20 +00:00
"path/filepath"
2015-09-13 11:14:18 +00:00
"strings"
2015-09-12 08:52:41 +00:00
2015-09-13 11:14:18 +00:00
"github.com/hacdias/caddy-hugo/assets"
"github.com/hacdias/caddy-hugo/edit"
2015-09-12 08:52:41 +00:00
"github.com/mholt/caddy/config/setup"
"github.com/mholt/caddy/middleware"
2015-09-12 21:18:29 +00:00
"github.com/spf13/hugo/commands"
2015-09-12 08:52:41 +00:00
)
2015-09-12 12:05:31 +00:00
// Setup function
2015-09-12 08:52:41 +00:00
func Setup(c *setup.Controller) (middleware.Middleware, error) {
2015-09-12 12:05:31 +00:00
commands.Execute()
2015-09-12 10:33:39 +00:00
2015-09-12 08:52:41 +00:00
return func(next middleware.Handler) middleware.Handler {
2015-09-12 17:58:10 +00:00
return &handler{Next: next}
2015-09-12 08:52:41 +00:00
}, nil
}
2015-09-12 13:08:48 +00:00
type handler struct{ Next middleware.Handler }
2015-09-12 08:52:41 +00:00
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
2015-09-13 11:14:18 +00:00
if urlMatch(r, "/admin") {
return route(w, r)
2015-09-12 12:05:31 +00:00
}
2015-09-12 13:16:15 +00:00
return h.Next.ServeHTTP(w, r)
2015-09-12 12:05:31 +00:00
}
2015-09-13 11:14:18 +00:00
func route(w http.ResponseWriter, r *http.Request) (int, error) {
page := parseComponents(r)[1]
2015-09-13 11:14:18 +00:00
if page == "assets" {
2015-09-13 19:37:20 +00:00
filename := strings.Replace(r.URL.Path, assetsURL, "static", 1)
file, err := assets.Asset(filename)
2015-09-13 11:14:18 +00:00
if err != nil {
return 404, nil
}
2015-09-13 19:37:20 +00:00
extension := filepath.Ext(filename)
mime := mime.TypeByExtension(extension)
header := w.Header()
header.Set("Content-Type", mime)
2015-09-13 11:14:18 +00:00
w.Write(file)
} else if page == "content" {
w.Write([]byte("Content Page"))
} else if page == "browse" {
w.Write([]byte("Show Data Folder"))
} else if page == "edit" {
return edit.Execute(w, r)
} else if page == "settings" {
w.Write([]byte("Settings Page"))
2015-09-13 11:14:18 +00:00
} else {
return 404, nil
}
return 200, nil
}
func parseComponents(r *http.Request) []string {
//The URL that the user queried.
path := r.URL.Path
path = strings.TrimSpace(path)
//Cut off the leading and trailing forward slashes, if they exist.
//This cuts off the leading forward slash.
if strings.HasPrefix(path, "/") {
path = path[1:]
}
//This cuts off the trailing forward slash.
if strings.HasSuffix(path, "/") {
cutOffLastCharLen := len(path) - 1
path = path[:cutOffLastCharLen]
}
//We need to isolate the individual components of the path.
components := strings.Split(path, "/")
return components
2015-09-13 11:14:18 +00:00
}