filebrowser/caddy/filemanager/filemanager.go

55 lines
1.3 KiB
Go
Raw Normal View History

2017-06-26 14:39:35 +00:00
// Package filemanager provides middleware for managing files in a directory
// when directory path is requested instead of a specific file. Based on browse
// middleware.
package filemanager
import (
"net/http"
2017-08-14 17:35:25 +00:00
"github.com/hacdias/filemanager"
"github.com/hacdias/filemanager/caddy/parser"
2017-06-26 14:39:35 +00:00
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
func init() {
caddy.RegisterPlugin("filemanager", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
2017-07-01 07:36:28 +00:00
type plugin struct {
2017-06-26 14:39:35 +00:00
Next httpserver.Handler
2017-08-14 17:35:25 +00:00
Configs []*filemanager.FileManager
2017-06-26 14:39:35 +00:00
}
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
2017-07-01 07:36:28 +00:00
func (f plugin) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
2017-06-26 14:39:35 +00:00
for i := range f.Configs {
// Checks if this Path should be handled by File Manager.
2017-08-14 17:35:25 +00:00
if !httpserver.Path(r.URL.Path).Matches(f.Configs[i].BaseURL) {
2017-06-26 14:39:35 +00:00
continue
}
2017-07-25 10:57:27 +00:00
f.Configs[i].ServeHTTP(w, r)
return 0, nil
2017-06-26 14:39:35 +00:00
}
return f.Next.ServeHTTP(w, r)
}
// setup configures a new FileManager middleware instance.
func setup(c *caddy.Controller) error {
2017-08-14 17:35:25 +00:00
configs, err := parser.Parse(c, "")
2017-06-26 14:39:35 +00:00
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
2017-07-01 07:36:28 +00:00
return plugin{Configs: configs, Next: next}
2017-06-26 14:39:35 +00:00
})
return nil
}