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 (s *Server) routes() {
s.mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
err := s.tmpl.ExecuteTemplate(w, "index.html", nil)
if err != nil {
log.Printf("Error with template: %s", err.Error())
return
}
})
}
func (s *Server) Serve(addr string) error {
httpSrv := &http.Server{
Addr: addr,
Handler: logRequests(s.mux),
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Printf("Server \"%s\" listening at %s", s.config.Name, addr)
return httpSrv.ListenAndServe()
}
func New(c *Config) *Server {
s := &Server{
config: c,
mux: http.NewServeMux(),
tmpl: template.Must(template.ParseFS(web.Files, "templates/*.html")),
}
s.routes()
return s
}