summaryrefslogtreecommitdiff
path: root/pkg/web/server.go
blob: e553920a1338e04713edf265b70338a38640dcc5 (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
package web

import (
	"net/http"

	"github.com/google/jsonapi"
	"github.com/xlgmokha/x/pkg/serde"
	"gitlab.com/mokhax/sparkled/pkg/db"
)

type Server struct {
	db         db.Repository
	fileserver http.Handler
}

func NewServer(storage db.Repository) *Server {
	http.NewServeMux()
	return &Server{
		db:         storage,
		fileserver: http.FileServer(http.Dir("public")),
	}
}

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.URL.String() {
	case "/health":
		w.WriteHeader(http.StatusOK)
	case "/sparkles.json":
		switch r.Method {
		case "GET":
			w.Header().Set("Content-Type", jsonapi.MediaType)
			serde.ToJSONAPI(w, s.db.All())
		}
	default:
		s.fileserver.ServeHTTP(w, r)
		break
	}
}