Files
zurg/internal/net/router.go
2023-11-21 13:10:48 +01:00

71 lines
1.9 KiB
Go

package net
import (
"net/http"
"path"
"strings"
"github.com/debridmediamanager.com/zurg/internal/config"
"github.com/debridmediamanager.com/zurg/internal/dav"
zurghttp "github.com/debridmediamanager.com/zurg/internal/http"
"github.com/debridmediamanager.com/zurg/internal/torrent"
"github.com/debridmediamanager.com/zurg/internal/universal"
"github.com/debridmediamanager.com/zurg/pkg/logutil"
"github.com/hashicorp/golang-lru/v2/expirable"
)
// Router creates a WebDAV router
func Router(mux *http.ServeMux, c config.ConfigInterface, t *torrent.TorrentManager, cache *expirable.LRU[string, string]) {
log := logutil.NewLogger().Named("net")
mux.HandleFunc("/http/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
requestPath := path.Clean(r.URL.Path)
if countNonEmptySegments(strings.Split(requestPath, "/")) > 3 {
universal.HandleGetRequest(w, r, t, c, cache)
} else {
zurghttp.HandleDirectoryListing(w, r, t)
}
case http.MethodHead:
universal.HandleHeadRequest(w, r, t, cache)
default:
log.Errorf("Request %s %s not supported yet", r.Method, r.URL.Path)
http.Error(w, "Method not implemented", http.StatusMethodNotAllowed)
}
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
davlog := logutil.NewLogger().Named("dav")
switch r.Method {
case "PROPFIND":
dav.HandlePropfindRequest(w, r, t, davlog)
case "DELETE":
dav.HandleDeleteRequest(w, r, t, davlog)
case http.MethodGet:
universal.HandleGetRequest(w, r, t, c, cache)
case http.MethodOptions:
w.WriteHeader(http.StatusOK)
default:
log.Errorf("Request %s %s not supported yet", r.Method, r.URL.Path)
http.Error(w, "Method not implemented", http.StatusMethodNotAllowed)
}
})
}
func countNonEmptySegments(urlSegments []string) int {
count := 0
for _, s := range urlSegments {
if s != "" {
count++
}
}
return count
}