1
0
mirror of https://github.com/lus/pasty.git synced 2023-08-10 21:13:09 +03:00
pasty/internal/web/frontend_server.go

78 lines
1.6 KiB
Go
Raw Normal View History

2023-06-08 20:17:34 +03:00
package web
import (
"embed"
"errors"
"io"
"io/fs"
"mime"
"net/http"
"path/filepath"
"strconv"
"strings"
)
//go:embed frontend/*
var frontend embed.FS
func frontendHandler(notFoundHandler http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
path := strings.TrimSpace(strings.TrimSuffix(request.URL.Path, "/"))
isFirstLevel := strings.Count(path, "/") <= 1
file, err := frontend.Open(filepath.Join("frontend", path))
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
if isFirstLevel {
serveIndexFile(writer, request)
} else {
notFoundHandler(writer, request)
}
return
}
2023-06-17 18:00:44 +03:00
writeErr(request, writer, err)
2023-06-08 20:17:34 +03:00
return
}
defer func() {
_ = file.Close()
}()
fileInfo, err := file.Stat()
if err != nil {
2023-06-17 18:00:44 +03:00
writeErr(request, writer, err)
2023-06-08 20:17:34 +03:00
return
}
if fileInfo.IsDir() {
if isFirstLevel {
serveIndexFile(writer, request)
} else {
notFoundHandler(writer, request)
}
return
}
content, err := io.ReadAll(file)
if err != nil {
2023-06-17 18:00:44 +03:00
writeErr(request, writer, err)
2023-06-08 20:17:34 +03:00
return
}
2023-06-08 20:55:43 +03:00
writer.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(fileInfo.Name())))
2023-06-08 20:17:34 +03:00
writer.Header().Set("Content-Length", strconv.Itoa(len(content)))
_, _ = writer.Write(content)
}
}
2023-06-17 18:00:44 +03:00
func serveIndexFile(writer http.ResponseWriter, request *http.Request) {
2023-06-08 20:17:34 +03:00
indexFile, err := frontend.ReadFile("frontend/index.html")
if err != nil {
2023-06-17 18:00:44 +03:00
writeErr(request, writer, err)
2023-06-08 20:17:34 +03:00
return
}
writer.Header().Set("Content-Type", "text/html")
writer.Header().Set("Content-Length", strconv.Itoa(len(indexFile)))
_, _ = writer.Write(indexFile)
}