summaryrefslogtreecommitdiff
path: root/server.go
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2024-05-07 20:54:33 +0200
committerxengineering <me@xengineering.eu>2024-05-07 20:54:33 +0200
commitebb446f6115b4ca690ea354fa4275e33a0d9976b (patch)
tree6c15fdf2dc8fe3475c1806f0d7d282a461dfa289 /server.go
parent5f5626314a40a47f53773f386e90e3bb6adfa96a (diff)
downloadceres-ebb446f6115b4ca690ea354fa4275e33a0d9976b.tar
ceres-ebb446f6115b4ca690ea354fa4275e33a0d9976b.tar.zst
ceres-ebb446f6115b4ca690ea354fa4275e33a0d9976b.zip
Move HTTP server code to new server.go file
This separates the main control flow and HTTP-related high-level code. Furthermore the new main.Server type makes the related methods and function more like the functions from the standard library with a NewServer() function and methods with only one word as name.
Diffstat (limited to 'server.go')
-rw-r--r--server.go64
1 files changed, 64 insertions, 0 deletions
diff --git a/server.go b/server.go
new file mode 100644
index 0000000..32d22b1
--- /dev/null
+++ b/server.go
@@ -0,0 +1,64 @@
+package main
+
+import (
+ "context"
+ "embed"
+ "log"
+ "net/http"
+
+ "xengineering.eu/ceres/controller"
+ "xengineering.eu/ceres/view"
+
+ "github.com/gorilla/mux"
+)
+
+type Server struct {
+ backend *http.Server
+}
+
+//go:embed view/static/simple.css/simple.css view/static/ceres.js
+var static embed.FS
+
+func NewServer(addr string) Server {
+ var r *mux.Router = mux.NewRouter()
+
+ r.PathPrefix("/static/").
+ Handler(http.StripPrefix("/static/", http.FileServer(http.FS(static))))
+
+ r.HandleFunc("/version", view.VersionRead(gitDescribe)).Methods(`GET`)
+
+ r.HandleFunc("/recipes", view.RecipesRead).Methods(`GET`)
+
+ r.HandleFunc("/recipe", controller.RecipeCreate).Methods(`POST`)
+ r.HandleFunc("/recipe/{id:[0-9]+}", view.RecipeRead).Methods(`GET`)
+ r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeUpdate).Methods(`POST`)
+ r.HandleFunc("/recipe/{id:[0-9]+}", controller.RecipeDelete).Methods(`DELETE`)
+
+ r.HandleFunc("/favicon.ico", view.FaviconRead).Methods(`GET`)
+
+ r.HandleFunc("/", view.IndexRead).Methods(`GET`)
+
+ muxer := http.NewServeMux()
+ muxer.Handle("/", r)
+
+ var srv http.Server
+ srv.Addr = addr
+ srv.Handler = muxer
+
+ log.Printf("Configured server to listen on http://%s\n", srv.Addr)
+
+ return Server{backend: &srv}
+}
+
+func (s Server) Start() {
+ s.backend.ListenAndServe()
+}
+
+func (s Server) Stop() {
+ err := s.backend.Shutdown(context.Background())
+ if err != nil {
+ log.Printf("Failed to shutdown HTTP server: %v\n", err)
+ } else {
+ log.Println("Stopped HTTP server")
+ }
+}