aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/server/server.go
blob: 8b66e62a2c1ee6ec055d9e77bc635ac3546454d2 (plain) (blame)
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
package server

import (
	"bytes"
	"io"
	"log/slog"
	"net/http"
	"strings"

	"github.com/jpappel/atlas/pkg/data"
	"github.com/jpappel/atlas/pkg/index"
	"github.com/jpappel/atlas/pkg/query"
)

func info(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(`
	<h1>Atlas Server</h1>
	<p>This is the experimental atlas server!
	Try POSTing a query to <pre>/search</pre></p>
	`))
}

func New(db *data.Query) *http.ServeMux {
	mux := http.NewServeMux()

	mux.HandleFunc("/", info)
	mux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
		b := &strings.Builder{}
		if _, err := io.Copy(b, r.Body); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Error processing request"))
			slog.Error("Error reading request body", slog.String("err", err.Error()))
			return
		}
		artifact, err := query.Compile(b.String(), 0, 1)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(err.Error()))
			slog.Error("Error compiling query", slog.String("err", err.Error()))
			return
		}

		pathDocs, err := db.Execute(artifact)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Error executing query"))
			slog.Error("Error executing query", slog.String("err", err.Error()))
			return
		}
		docs := make([]*index.Document, 0, len(pathDocs))
		for _, doc := range pathDocs {
			docs = append(docs, doc)
		}

		var buf bytes.Buffer
		_, err = query.JsonOutput{}.OutputTo(&buf, docs)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Error while writing output"))
			slog.Error("Error writing json output", slog.String("err", err.Error()))
		}

		io.Copy(w, &buf)
	})

	return mux
}