Brijesh's Git Server — watchman @ 070e9230ef8032862eb09dd029f6d4f39705b547

observability tool, needs to be rewritten once identity is stable

main.go (view raw)

 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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"watchman/internal"
	"watchman/middleware"
	"watchman/schema"
	"watchman/utils"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	config := utils.ReadConfig()

	dbConnection, err := sql.Open("sqlite3", "./watchman.db")
	if err != nil {
		panic(err)
	}
	defer dbConnection.Close()

	multiplexer := http.NewServeMux()

	multiplexer.HandleFunc("/health", utils.HealthCheckHandler)

	multiplexer.HandleFunc("/projects", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodPost:
			internal.CreateProject(w, r, dbConnection)
		case http.MethodGet:
			internal.ListAllProjects(w, r, dbConnection)
		default:
			utils.MethodNotAllowedHandler(w, r)
		}
	})

	multiplexer.HandleFunc("/projects/", func(w http.ResponseWriter, r *http.Request) {
		url := strings.TrimPrefix(r.URL.Path, "/projects/")
		projectID := url

		if projectID == "" {
			response := schema.ResponseType{
				Status:    "ERROR",
				Message:   "Project ID not provided",
				RequestID: r.Context().Value(schema.RequestIDKey{}).(string),
			}

			w.WriteHeader(http.StatusBadRequest)
			w.Header().Set("Content-Type", "application/json")
			err = json.NewEncoder(w).Encode(response)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}

		switch r.Method {
		case http.MethodGet:
			internal.GetProjectByID(w, r, dbConnection, projectID)
		case http.MethodPut:
			internal.UpdateProjectByID(w, r, dbConnection, projectID)
		case http.MethodDelete:
			internal.DeleteProjectByID(w, r, dbConnection, projectID)
		default:
			utils.MethodNotAllowedHandler(w, r)
		}
	})

	multiplexer.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodPost:
			internal.BatchInsertLogs(w, r, dbConnection)
		case http.MethodGet:
			internal.GetLogs(w, r, dbConnection)
		case http.MethodDelete:
			internal.DeleteLogs(w, r, dbConnection)
		default:
			utils.MethodNotAllowedHandler(w, r)
		}
	})

	multiplexer.HandleFunc("/login", internal.AdminLogin)

	fmt.Println("Starting server on port " + strconv.Itoa(config.Port))
	log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Port),
		middleware.CorsMiddleware(
			middleware.RequestIDMiddleware(
				middleware.Ratelimit(
					config,
					multiplexer,
				)))))
}