feat: first frontend implementation

This commit is contained in:
Florian Sylvain
2023-08-08 05:14:31 +02:00
parent 91d82b0ad7
commit dad0c906f0
9 changed files with 307 additions and 36 deletions
+52 -12
View File
@@ -4,8 +4,9 @@ import (
"GohCMS2/api"
"encoding/json"
"fmt"
"github.com/MadAppGang/httplog"
"github.com/go-chi/chi/v5"
"github.com/go-chi/httplog"
"github.com/go-chi/cors"
"github.com/go-chi/jwtauth/v5"
"net/http"
)
@@ -17,6 +18,13 @@ func jsonContentTypeMiddleware(next http.Handler) http.Handler {
})
}
func htmlContentTypeMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
next.ServeHTTP(w, r)
})
}
func initJwt() {
api.TokenAuth = jwtauth.New("HS256", []byte("secret"), nil)
}
@@ -26,29 +34,61 @@ func getHelloWorld(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(msg)
}
func main() {
api.InitContainer()
api.InitValidator()
initJwt()
func initBackendRoutes() *chi.Mux {
r := chi.NewRouter()
r.Get("/", getHelloWorld)
r.Use(httplog.LoggerWithName("backend"))
r.Use(jsonContentTypeMiddleware)
r.Get("/", getHelloWorld)
r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(api.TokenAuth))
r.Use(jwtauth.Authenticator)
r.Mount("/article", api.NewArticleRouter())
})
r.Mount("/auth", api.NewAuthRouter())
return r
}
func initFrontendRoutes() *chi.Mux {
r := chi.NewRouter()
r.Use(httplog.LoggerWithName("frontend"))
r.Use(htmlContentTypeMiddleware)
r.Mount("/", api.NewPageRouter())
return r
}
func initRoutes() *chi.Mux {
backend := initBackendRoutes()
frontend := initFrontendRoutes()
apiRouter := chi.NewRouter()
apiRouter.Use(httplog.RequestLogger(httplog.NewLogger("GohCMS2")))
apiRouter.Use(jsonContentTypeMiddleware)
apiRouter.Mount("/v1", r)
// TODO use env variable for allowed origins
apiRouter.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: false,
MaxAge: 300,
}))
apiRouter.Mount("/v1", backend)
apiRouter.Mount("/", frontend)
return apiRouter
}
func main() {
api.InitContainer()
api.InitValidator()
initJwt()
router := initRoutes()
fmt.Println("Server starting on port 8080")
err := http.ListenAndServe(":8080", apiRouter)
err := http.ListenAndServe(":8080", router)
if err != nil {
panic(err)
}