commit f345ecb7d63c0f0287d21ec492c24259d1123b61
Author: lovezsh <1942314542@qq.com>
Date: Sat Dec 9 23:15:51 2023 +0800
init
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a700ef1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,3 @@
+## 简介
+
+一个简单的文件浏览服务
\ No newline at end of file
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..98e1996
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module filebrowser
+
+go 1.21.3
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..55443a7
--- /dev/null
+++ b/index.html
@@ -0,0 +1,25 @@
+
+
+
+
+
+ Document
+
+
+ {{ if .Err }}
+ {{.Err}}
+ {{ else }}
+
+ {{ range .Entries }}
+ -
+ {{ if .IsDir }}
+ {{.Name}}/
+ {{ else }}
+ {{.Name}}
+ {{ end }}
+
+ {{ end }}
+
+ {{ end }}
+
+
\ No newline at end of file
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..7f100c9
--- /dev/null
+++ b/main.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "flag"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "text/template"
+
+ _ "embed"
+)
+
+type Entry struct {
+ Name string
+ IsDir bool
+}
+
+type Result struct {
+ Err string
+ Entries []Entry
+}
+
+//go:embed index.html
+var index string
+
+var tpl = template.Must(template.New("index.html").Parse(index))
+
+func Render(w http.ResponseWriter, data interface{}) {
+ w.Header().Set("Content-Type", "text/html;charset=utf8")
+ if err := tpl.Execute(w, data); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+}
+
+func View(w http.ResponseWriter, r *http.Request) {
+ log.Println(r.URL.Path)
+
+ path := filepath.Join(*dir, filepath.Clean(r.URL.Path))
+
+ if !strings.HasSuffix(r.URL.Path, "/") {
+ w.Header().Add("Content-Disposition", fmt.Sprintf("attachment;filename=%s", filepath.Base(path)))
+ http.ServeFile(w, r, path)
+ return
+ }
+
+ entries, err := os.ReadDir(path)
+ if err != nil {
+ Render(w, &Result{Err: err.Error()})
+ return
+ }
+
+ items := make([]Entry, 0)
+ for _, entry := range entries {
+ items = append(items, Entry{
+ Name: entry.Name(),
+ IsDir: entry.IsDir(),
+ })
+ }
+ Render(w, &Result{Entries: items})
+}
+
+var (
+ dir = flag.String("dir", "./", "server file directory")
+ listen = flag.String("listen", ":3000", "listen address")
+)
+
+func main() {
+ flag.Parse()
+
+ http.HandleFunc("/", View)
+ log.Printf("server listen at %s", *listen)
+ log.Fatal(http.ListenAndServe(*listen, nil))
+}