lenslocked/main.go

59 lines
1.5 KiB
Go

package main
import (
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func executeTemplate(w http.ResponseWriter, filepath string) {
w.Header().Set("Content-Type", "text/html; charset=utf8")
tpl, err := template.ParseFiles(filepath)
if err != nil {
log.Printf("Error parsing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
err = tpl.Execute(w, nil)
if err != nil {
log.Printf("Error executing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
path := filepath.Join("templates", "home.gohtml")
executeTemplate(w, path)
}
func contactHandler(w http.ResponseWriter, r *http.Request) {
path := filepath.Join("templates", "contact.gohtml")
executeTemplate(w, path)
}
func faqHandler(w http.ResponseWriter, r *http.Request) {
path := filepath.Join("templates", "faq.gohtml")
executeTemplate(w, path)
}
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf8")
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 page not found")
}
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/", homeHandler)
r.Get("/contact", contactHandler)
r.Get("/faq", faqHandler)
r.NotFound(notFoundHandler)
fmt.Println("Starting the server on :3000...")
http.ListenAndServe(":3000", r)
}