This commit is contained in:
Artur Gurgul 2025-04-25 15:43:46 +02:00
parent a0a338067b
commit a124790b49
5 changed files with 99 additions and 48 deletions

7
install.sh Normal file
View file

@ -0,0 +1,7 @@
go build -o webdav ./src
export WEBDAV_SERV_PORT=8880
export TEST_DRIVE_PATH=/Users/artur/test-drive
./webdav

View file

@ -1,47 +1,71 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
//"strings"
"html/template" "html/template"
"os" "os"
"encoding/json" "encoding/json"
"path/filepath"
) )
var templates = template.Must(template.ParseGlob("templates/*.html")) var templates = template.Must(template.ParseGlob("templates/*.html"))
// curl -H "Accept: application/json" http://localhost:9988/
func getRoot(w http.ResponseWriter, r *http.Request) { func getRoot(w http.ResponseWriter, r *http.Request) {
fmt.Printf("got / request\n") // Read optional path parameter
//io.WriteString(w, "This is my website!\n") //subPath := r.URL.Query().Get("path")
//requestedPath := strings.TrimPrefix(r.URL.Path, "/file/")
requestedPath := r.URL.Path
basePath := GetDefaultPath()
c := ListFiles("") fullPath := filepath.Join(basePath, requestedPath)
fmt.Println(c)
context := struct {
IsLoggedIn bool ; Files []struct {FileName string}}{ info, err := os.Stat(fullPath)
IsLoggedIn: false, if err != nil {
Files: c, fmt.Println(err)
http.NotFound(w, r)
return
}
if info.IsDir() {
} else {
http.ServeFile(w, r, fullPath)
return
}
fmt.Println("F: ", requestedPath)
fmt.Println("A: ", basePath)
fmt.Println("FP: ", fullPath)
fmt.Println("FP: ", info)
c := ListFiles(fullPath)
context := struct {
IsLoggedIn bool
Files []FSNode
Path string
}{
IsLoggedIn: false,
Files: c,
Path: requestedPath,
} }
// Check if request wants JSON
if r.Header.Get("Accept") == "application/json" { if r.Header.Get("Accept") == "application/json" {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(context) json.NewEncoder(w).Encode(context)
return return
} }
//tmpl, _ := templates.ParseFiles("templates/venue.html")
templates.ExecuteTemplate(w, "index.html", context) templates.ExecuteTemplate(w, "index.html", context)
} }
func ListFiles(dir string) []struct {FileName string} { func ListFiles(dir string) []FSNode {
context := []struct {FileName string} {} context := []FSNode {}
entries, err := os.ReadDir(".") entries, err := os.ReadDir(dir)
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
return context return context
@ -53,9 +77,21 @@ func ListFiles(dir string) []struct {FileName string} {
fmt.Println("Error getting info:", err) fmt.Println("Error getting info:", err)
continue continue
} }
kind := "Folder"
context = append(context, struct {FileName string}{ if !entry.IsDir() {
FileName: info.Name(), ext := filepath.Ext(entry.Name())
if ext != "" {
kind = ext[1:] + " File" // e.g. "txt File"
} else {
kind = "Unknown File"
}
}
context = append(context, FSNode{
FileName: entry.Name(),
IsDir: entry.IsDir(),
ModTime: info.ModTime().Format("Jan 02, 2006 15:04"),
Size: fmt.Sprintf("%d KB", info.Size()/1024),
Kind: kind,
}) })
//fmt.Printf("Name: %s, Size: %d bytes, IsDir: %t\n", info.Name(), info.Size(), info.IsDir()) //fmt.Printf("Name: %s, Size: %d bytes, IsDir: %t\n", info.Name(), info.Size(), info.IsDir())
@ -64,30 +100,7 @@ func ListFiles(dir string) []struct {FileName string} {
return context return context
} }
func getHello(w http.ResponseWriter, r *http.Request) {
fmt.Printf("got /hello request\n")
io.WriteString(w, "Hello, HTTP!\n")
}
func GetMenusHandler(w http.ResponseWriter, r *http.Request) { func GetMenusHandler(w http.ResponseWriter, r *http.Request) {
//fmt.Fprintf(w, "Hello, World!") //fmt.Fprintf(w, "Hello, World!")
templates.ExecuteTemplate(w, "index.html", nil) templates.ExecuteTemplate(w, "index.html", nil)
} }
func HTTPmain() {
http.HandleFunc("/", getRoot)
http.HandleFunc("/hello", getHello)
err := http.ListenAndServe(":3333", nil)
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
} else if err != nil {
fmt.Printf("error starting server: %s\n", err)
os.Exit(1)
}
}

View file

@ -16,11 +16,20 @@ import (
"golang.org/x/net/webdav" "golang.org/x/net/webdav"
) )
func GetDefaultPath() string {
drivePath := os.Getenv("TEST_DRIVE_PATH")
if drivePath == "" {
drivePath = "."
}
return drivePath
}
// WebDAV handler with authentication // WebDAV handler with authentication
func webdavHandler(w http.ResponseWriter, r *http.Request) { func webdavHandler(w http.ResponseWriter, r *http.Request) {
if runtime.GOOS != "linux" { if runtime.GOOS != "linux" {
drivePath := GetDefaultPath()
handler := &webdav.Handler{ handler := &webdav.Handler{
FileSystem: webdav.Dir("."), FileSystem: webdav.Dir(drivePath),
LockSystem: webdav.NewMemLS(), LockSystem: webdav.NewMemLS(),
} }
handler.ServeHTTP(w, r) handler.ServeHTTP(w, r)

9
src/models.go Normal file
View file

@ -0,0 +1,9 @@
package main
type FSNode struct {
FileName string
IsDir bool
ModTime string
Size string
Kind string
}

View file

@ -11,13 +11,26 @@
<p>Please log in to access more features.</p> <p>Please log in to access more features.</p>
{{end}} {{end}}
<h2>Files</h2> <h2>Files at: {{$.Path}}</h2>
{{if .Files}} {{if .Files}}
<ul> <table border="1" cellpadding="5" cellspacing="0">
<tr>
<th>Name</th>
<th>Modified</th>
<th>Size</th>
<th>Kind</th>
</tr>
{{range .Files}} {{range .Files}}
<li>{{.FileName}}</li> <tr>
<td>
<a href="{{$.Path}}/{{.FileName}}">{{.FileName}}</a>
</td>
<td>{{.ModTime}}</td>
<td>{{.Size}}</td>
<td>{{.Kind}}</td>
</tr>
{{end}} {{end}}
</ul> </table>
{{else}} {{else}}
<p>No files available.</p> <p>No files available.</p>
{{end}} {{end}}