small fix

This commit is contained in:
dedal.qq 2023-07-01 13:01:01 +03:00
parent d0344aff9e
commit 914d9d0b54
8 changed files with 54 additions and 44 deletions

0
build/.gitignore vendored Normal file
View File

View File

@ -5,6 +5,8 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"file-server/internal/handler"
) )
var port uint var port uint
@ -17,18 +19,20 @@ func init() {
} }
func main() { func main() {
if folderPath == "" { if folderPath == "" {
fmt.Fprintf(os.Stderr, "Error: parametr 'path' is required") fmt.Fprintf(os.Stderr, "Error: parametr 'path' is required")
os.Exit(1) os.Exit(1)
} }
server := &http.Server{ server := &http.Server{
Addr: fmt.Sprintf(":%d", port), Addr: fmt.Sprintf(":%d", port),
Handler: &fileHandler{ Handler: handler.NewHandler(folderPath),
root: folderPath,
},
} }
server.ListenAndServe() err := server.ListenAndServe()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v", err)
os.Exit(1)
}
} }

12
ev.json
View File

@ -1,12 +0,0 @@
{
"build": [
["make"]
],
"services": [
{
"name": "files-server",
"restart_after_update": true,
"cmd": ["./files-server", "-p", "/var/files/", "-l", "8745"]
}
]
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module file-server
go 1.20

View File

@ -1,4 +1,4 @@
package main package handler
import ( import (
"fmt" "fmt"
@ -8,7 +8,6 @@ import (
"net/url" "net/url"
"os" "os"
"path" "path"
"path/filepath"
"sort" "sort"
"strings" "strings"
) )
@ -49,18 +48,18 @@ func localRedirect(w http.ResponseWriter, r *http.Request, newPath string) {
} }
func toHTTPError(err error) (msg string, httpStatus int) { func toHTTPError(err error) (msg string, httpStatus int) {
if os.IsNotExist(err) { switch {
case os.IsNotExist(err):
return "404 page not found", http.StatusNotFound return "404 page not found", http.StatusNotFound
} case os.IsPermission(err):
if os.IsPermission(err) {
return "403 Forbidden", http.StatusForbidden return "403 Forbidden", http.StatusForbidden
default:
return "500 Internal Server Error", http.StatusInternalServerError
} }
// Default:
return "500 Internal Server Error", http.StatusInternalServerError
} }
func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string) { func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, filePath string) {
f, err := fs.Open(name) f, err := fs.Open(filePath)
if err != nil { if err != nil {
msg, code := toHTTPError(err) msg, code := toHTTPError(err)
renderError(w, msg, code) renderError(w, msg, code)
@ -86,7 +85,7 @@ func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name
// Still a directory? (we didn't find an index.html file) // Still a directory? (we didn't find an index.html file)
if d.IsDir() { if d.IsDir() {
dirList(w, r, f, name, fs) dirList(w, r, f, fs, filePath)
return return
} }
@ -95,7 +94,7 @@ func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name
http.ServeContent(w, r, d.Name(), d.ModTime(), f) http.ServeContent(w, r, d.Name(), d.ModTime(), f)
} }
func dirList(w http.ResponseWriter, r *http.Request, f http.File, name string, fs http.FileSystem) { func dirList(w http.ResponseWriter, r *http.Request, f http.File, fs http.FileSystem, filePath string) {
dirs, err := f.Readdir(-1) dirs, err := f.Readdir(-1)
if err != nil { if err != nil {
renderError(w, "Error reading directory", http.StatusInternalServerError) renderError(w, "Error reading directory", http.StatusInternalServerError)
@ -110,35 +109,39 @@ func dirList(w http.ResponseWriter, r *http.Request, f http.File, name string, f
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
t, err := template.New("main.html").ParseFiles("main.html") t, err := template.New("main.html").ParseFiles("static/main.html")
if err != nil { if err != nil {
fmt.Printf(err.Error()) fmt.Printf(err.Error())
return return
} }
data := &Data{ data := &Data{
Title: name, Title: filePath,
IsRoot: name == "/", IsRoot: filePath == "/",
Files: make([]*File, 0, len(dirs)), Files: make([]*File, 0, len(dirs)),
Readme: loadReadmeFile(name, fs),
} }
for _, d := range dirs { for _, d := range dirs {
name := d.Name() fileName := d.Name()
icon := "file" icon := "file"
size := byteCountBinary(d.Size()) size := byteCountBinary(d.Size())
if d.IsDir() { if d.IsDir() {
name += "/" fileName += "/"
icon = "folder" icon = "folder"
size = "-" size = "-"
} }
url := url.URL{Path: name} if !d.IsDir() && strings.HasPrefix(strings.ToLower(fileName), "readme.") {
data.Readme = loadReadmeFile(fs, filePath+"/"+fileName)
}
url := url.URL{Path: fileName}
data.Files = append(data.Files, &File{ data.Files = append(data.Files, &File{
Icon: icon, Icon: icon,
URL: url.String(), URL: url.String(),
Name: htmlReplacer.Replace(name), Name: htmlReplacer.Replace(fileName),
Size: size, Size: size,
Date: d.ModTime().Format("02.01.2006 15:04:05"), Date: d.ModTime().Format("02.01.2006 15:04:05"),
}) })
@ -152,8 +155,8 @@ func dirList(w http.ResponseWriter, r *http.Request, f http.File, name string, f
} }
func loadReadmeFile(path string, fs http.FileSystem) string { func loadReadmeFile(fs http.FileSystem, fileName string) string {
f, err := fs.Open(filepath.Join(path, "readme.txt")) f, err := fs.Open(fileName)
if err != nil { if err != nil {
return "" return ""
} }
@ -166,14 +169,22 @@ func loadReadmeFile(path string, fs http.FileSystem) string {
} }
type fileHandler struct { type fileHandler struct {
root string rootPath string
}
func NewHandler(rootPath string) http.Handler {
return &fileHandler{
rootPath: rootPath,
}
} }
func (fh *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (fh *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path upath := r.URL.Path
if !strings.HasPrefix(upath, "/") { if !strings.HasPrefix(upath, "/") {
upath = "/" + upath upath = "/" + upath
r.URL.Path = upath r.URL.Path = upath
} }
serveFile(w, r, http.Dir(fh.root), path.Clean(upath))
serveFile(w, r, http.Dir(fh.rootPath), path.Clean(upath))
} }

View File

@ -1,4 +1,4 @@
package main package handler
// File - // File -
type File struct { type File struct {

View File

@ -1,4 +1,8 @@
.PHONY: build
all: build all: build
build: build: build/files-server
go build -o files-server
build/files-server: cmd/file-server/main.go internal/handler/*.go
go build -o build/files-server cmd/file-server/main.go