Files
server/main.go
Konstantin Grachev edde11aace
All checks were successful
Build and Push / build-and-push (push) Successful in 22s
feat: add .html extension
2025-07-18 23:03:55 +03:00

72 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"embed"
"io/fs"
"log"
"net/http"
"path/filepath"
)
//go:embed public/*
var publicFS embed.FS
func main() {
// Используем подпапку 'public' из embed.FS
content, err := fs.Sub(publicFS, "public")
if err != nil {
log.Fatal(err)
}
// Создаем файловый сервер с нашим обработчиком расширений
fileServer := http.FileServer(neuterFileSystem{http.FS(content)})
http.Handle("/", fileServer)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// neuterFileSystem предотвращает листинг директорий и добавляет .html к URL без расширения
type neuterFileSystem struct {
fs http.FileSystem
}
func (n neuterFileSystem) Open(path string) (http.File, error) {
f, err := n.fs.Open(path)
if err != nil {
f, err = n.fs.Open(path + ".html")
}
if err != nil {
log.Println(err)
return nil, err
}
// Проверяем, не директория ли это
s, err := f.Stat()
if err != nil {
log.Println(err)
return nil, err
}
if s.IsDir() {
// Пробуем открыть index.html в директории
index := filepath.Join(path, "index.html")
if _, err := n.fs.Open(index); err != nil {
closeErr := f.Close()
if closeErr != nil {
log.Println(err)
return nil, closeErr
}
log.Println(err)
return nil, err
}
}
return f, nil
}