summaryrefslogtreecommitdiff
path: root/internal/server/handler/handler.go
blob: a108f93281aeea36a7240b501acb677e9b20585b (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package handler

import (
	"context"
	"fmt"
	"io"
	"net/http"

	"codeberg.org/snonux/gos/internal/config/server"
	"codeberg.org/snonux/gos/internal/server/repository"
	"codeberg.org/snonux/gos/internal/types"
)

type Handler struct {
	conf server.ServerConfig
}

func New(conf server.ServerConfig) Handler {
	return Handler{
		conf: conf,
	}
}

func (h Handler) Submit(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	if r.Method != "POST" {
		return fmt.Errorf("expected POST request, but got %s", r.Method)
	}

	bytes, err := io.ReadAll(r.Body)
	if err != nil {
		return err
	}

	entry, err := types.NewEntry(bytes)
	if err != nil {
		return err
	}
	return repository.Instance(h.conf).Merge(entry)
}

func (h Handler) List(w http.ResponseWriter, r *http.Request) error {
	if r.Method != "GET" {
		return fmt.Errorf("expexted GET request")
	}

	list, err := repository.Instance(h.conf).ListBytes()
	if err != nil {
		return err
	}

	_, err = w.Write(list)
	return err
}

func (h Handler) Get(w http.ResponseWriter, r *http.Request) error {
	json, err := repository.Instance(h.conf).GetJSON(r.URL.Query().Get("id"))
	if err != nil {
		return err
	}

	fmt.Fprint(w, json)
	return nil
}

func (h Handler) Merge(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	if err := repository.Instance(h.conf).MergeRemotely(ctx); err != nil {
		return err
	}

	fmt.Fprint(w, "Repository merge went well")
	return nil
}