This commit is contained in:
lovezsh 2023-12-09 23:15:51 +08:00
commit f345ecb7d6
4 changed files with 108 additions and 0 deletions

3
README.md Normal file
View File

@ -0,0 +1,3 @@
## 简介
一个简单的文件浏览服务

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module filebrowser
go 1.21.3

25
index.html Normal file
View File

@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{{ if .Err }}
<div style="color: red;">{{.Err}}</div>
{{ else }}
<ul>
{{ range .Entries }}
<li>
{{ if .IsDir }}
<a href="{{.Name}}/">{{.Name}}/</a>
{{ else }}
<a href="{{.Name}}">{{.Name}}</a>
{{ end }}
</li>
{{ end }}
</ul>
{{ end }}
</body>
</html>

77
main.go Normal file
View File

@ -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))
}