filebrowser/handlers/search.go
Henrique Dias 4cb3ff6ff2 implement #88 on back-end
Former-commit-id: 95c30bbefe3f97cbccc49b7e8d60ad20cee5d82f [formerly b8574b97cd6ffee5e3f473a10f7a97448d59f853] [formerly 133725ae36fdf64b270f9f5761a26e480f3ff189 [formerly de480c25bb4c77a7b9aa476a3e3a8a9e898d43f6]]
Former-commit-id: bd3547c5afb9420d29a54b21907d74d8f1c53164 [formerly 12676ba6a477473683255d9d1da445215d98ff38]
Former-commit-id: 2ccfbe9adb08aac188c90fe2ef8b47f659c3f4a8
2017-05-06 21:47:38 +01:00

82 lines
1.6 KiB
Go

package handlers
import (
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gorilla/websocket"
"github.com/hacdias/caddy-filemanager/config"
)
// Search ...
func Search(w http.ResponseWriter, r *http.Request, c *config.Config, u *config.User) (int, error) {
// Upgrades the connection to a websocket and checks for errors.
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return 0, err
}
defer conn.Close()
var (
search string
message []byte
)
caseInsensitive := (r.URL.Query().Get("insensitive") == "true")
// Starts an infinite loop until a valid command is captured.
for {
_, message, err = conn.ReadMessage()
if err != nil {
return http.StatusInternalServerError, err
}
if len(message) != 0 {
search = string(message)
break
}
}
if caseInsensitive {
search = strings.ToLower(search)
}
scope := strings.Replace(r.URL.Path, c.BaseURL, "", 1)
scope = strings.TrimPrefix(scope, "/")
scope = "/" + scope
scope = u.Scope + scope
scope = strings.Replace(scope, "\\", "/", -1)
scope = filepath.Clean(scope)
err = filepath.Walk(scope, func(path string, f os.FileInfo, err error) error {
if caseInsensitive {
path = strings.ToLower(path)
}
if strings.Contains(path, search) {
if !u.Allowed(path) {
return nil
}
path = strings.TrimPrefix(path, scope)
path = strings.Replace(path, "\\", "/", -1)
path = strings.TrimPrefix(path, "/")
err = conn.WriteMessage(websocket.TextMessage, []byte(path))
if err != nil {
return err
}
}
return nil
})
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}