package server
import (
"log"
"time"
"html/template"
"net/http"
"codeberg.org/mihna123/openstore/internal/web"
)
type Config struct {
Name string
}
type Server struct {
config *Config
tmpl *template.Template
mux *http.ServeMux
}
func New(config *Config) *Server {
tmpl := template.Must(template.ParseFS(web.Files, "templates/*.html"))
mux := http.NewServeMux()
return &Server{config, tmpl, mux}
}
func (s *Server) Serve(addr string) error {
s.mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
log.Printf("[%s] %s - %s", r.Method, r.RequestURI, r.RemoteAddr)
err := s.tmpl.ExecuteTemplate(w, "index.html", nil)
if err != nil {
log.Printf("Error with template: %s", err.Error())
return
}
})
httpSrv := http.Server{
Addr: addr,
Handler: s.mux,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Printf("Server \"%s\" listening at %s", s.config.Name, addr)
return httpSrv.ListenAndServe()
}