diff --git a/oblig1/main.go b/oblig1/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e382d2f2975e9576dd30517193a4b4fd0eb90bbf --- /dev/null +++ b/oblig1/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "main/endpoints" + "net/http" +) + +// EndpointHandler defines the structure of handlers. +type EndpointHandler func(http.ResponseWriter, *http.Request) + +func main() { + http.HandleFunc("/librarystats/v1/bookcount/", makeHandler(endpoints.BookCountHandler)) + http.HandleFunc("/librarystats/v1/readership/", makeHandler(endpoints.ReadershipHandler)) + http.HandleFunc("/librarystats/v1/status/", makeHandler(endpoints.StatusHandler)) + http.HandleFunc("/", makeHandler(endpoints.Errorhandler)) + + fmt.Println("Server is running on :8080...") + http.ListenAndServe(":8080", nil) +} + +// makeHandler is a wrapper to handle panics and set common headers. +func makeHandler(handler EndpointHandler) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + }() + + w.Header().Set("Content-Type", "application/json") + handler(w, r) + } +}