summaryrefslogtreecommitdiff
path: root/internal/server/server.go
blob: 6de45cac77c8b270a146113cd11eada1828cf9f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
}