Venus_Studios/main.go

109 lines
2.2 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
)
type pageRoute struct {
Path string
File string
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
root, err := filepath.Abs(".")
if err != nil {
log.Fatalf("resolve website directory: %v", err)
}
mux := http.NewServeMux()
registerPages(mux, root)
registerAssets(mux, root)
server := &http.Server{
Addr: ":" + port,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
fmt.Printf("Venus Photo Studio And Lab running on port %s\n", port)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("start server: %v", err)
}
}
func registerPages(mux *http.ServeMux, root string) {
pages := []pageRoute{
{Path: "/", File: "index.html"},
{Path: "/about", File: "about.html"},
{Path: "/gallery", File: "gallery.html"},
{Path: "/services", File: "services.html"},
{Path: "/contact", File: "contact.html"},
}
for _, page := range pages {
route := page
mux.HandleFunc(route.Path, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != route.Path {
http.NotFound(w, r)
return
}
servePage(w, r, filepath.Join(root, route.File))
})
}
redirects := map[string]string{
"/index.html": "/",
"/about.html": "/about",
"/gallery.html": "/gallery",
"/services.html": "/services",
"/contact.html": "/contact",
}
for from, to := range redirects {
target := to
mux.HandleFunc(from, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target, http.StatusMovedPermanently)
})
}
}
func registerAssets(mux *http.ServeMux, root string) {
fileServer := http.FileServer(http.Dir(root))
mux.Handle("/assets/", fileServer)
mux.HandleFunc("/tailwind.config.js", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join(root, "tailwind.config.js"))
})
}
func servePage(w http.ResponseWriter, r *http.Request, file string) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Cache-Control", "no-cache")
http.ServeFile(w, r, file)
}