summaryrefslogtreecommitdiff
path: root/cmd/tfstated/get.go
blob: 6de78a529aadb70e5edd2556f2e90ee011c0901b (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
package main

import (
	"database/sql"
	"errors"
	"fmt"
	"net/http"

	"git.adyxax.org/adyxax/tfstated/pkg/database"
)

func handleGet(db *database.DB) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-store, no-cache")
		w.Header().Set("Content-Type", "application/json")

		if r.URL.Path == "/" {
			w.WriteHeader(http.StatusBadRequest)
			_, _ = w.Write([]byte("{\"msg\": \"No state path provided, cannot GET /\"}"))
			return
		}

		if data, err := db.GetState(r.URL.Path); err != nil {
			if errors.Is(err, sql.ErrNoRows) {
				w.WriteHeader(http.StatusNotFound)
			} else {
				w.WriteHeader(http.StatusInternalServerError)
			}
			_, _ = w.Write([]byte(fmt.Sprintf("{\"msg\": \"%+v\"}", err)))
		} else {
			w.WriteHeader(http.StatusOK)
			_, _ = w.Write(data)
		}
	})
}