Setting up basic application structure
Some checks failed
My Actions / Explore (push) Has been cancelled

This commit is contained in:
2024-11-04 21:41:33 +01:00
parent 1a5a4f3ec9
commit 1cd303824d
15 changed files with 204 additions and 35 deletions

22
src/middleware/inertia.go Normal file
View File

@ -0,0 +1,22 @@
package middleware
import (
"fmt"
inertia "github.com/romsar/gonertia"
"net/http"
)
func InertiaMiddleware(i *inertia.Inertia) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
getContextData := r.Context().Value("data")
fmt.Println(getContextData)
err := i.Render(w, r, "Home/Index", inertia.Props{
"text": "From Golang",
})
if err != nil {
return
}
}
return http.HandlerFunc(fn)
}

15
src/middleware/logger.go Normal file
View File

@ -0,0 +1,15 @@
package middleware
import (
"context"
"fmt"
"net/http"
)
func TheLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(fmt.Sprintf("LOG: %s %s", r.Method, r.URL.Path))
ctx := context.WithValue(r.Context(), "data", "data:test")
next.ServeHTTP(w, r.WithContext(ctx))
})
}

15
src/routes/api.go Normal file
View File

@ -0,0 +1,15 @@
package routes
import (
"net/http"
"github.com/go-chi/chi/v5"
)
func Api() *chi.Mux {
r := chi.NewRouter()
r.Get("/version", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("V0.1"))
})
return r
}

22
src/routes/web.go Normal file
View File

@ -0,0 +1,22 @@
package routes
import (
"github.com/go-chi/chi/v5"
inertia "github.com/romsar/gonertia"
"homeautomation/webserver/src/middleware"
"log"
"net/http"
)
func Web() *chi.Mux {
r := chi.NewRouter()
i, err := inertia.NewFromFile("public/templates/root.html")
if err != nil {
log.Fatal(err)
}
r.Handle("/", i.Middleware(middleware.InertiaMiddleware(i)))
r.Handle("/hello", i.Middleware(middleware.InertiaMiddleware(i)))
r.Handle("/build/", http.StripPrefix("/build/", http.FileServer(http.Dir("./serve/build"))))
return r
}

24
src/server.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
HAmiddleware "homeautomation/webserver/src/middleware"
routes "homeautomation/webserver/src/routes"
)
func main() {
mux := chi.NewRouter()
// Setup Middleware
mux.Use(middleware.Compress(5, "text/html", "text/css"))
mux.Use(middleware.Heartbeat("/"))
mux.Use(middleware.Recoverer)
// Setup custom middleware
mux.Use(HAmiddleware.TheLogger)
// Define routes
mux.Mount("/", routes.Web())
mux.Mount("/api", routes.Api())
http.ListenAndServe(":8080", mux)
}