This commit is contained in:
Eden Kirin
2024-01-20 23:46:36 +01:00
commit 960c22a8c8
10 changed files with 319 additions and 0 deletions

5
app/handlers/home.go Normal file
View File

@ -0,0 +1,5 @@
package handlers
import "github.com/gin-gonic/gin"
func Home(c *gin.Context) {}

7
app/main.go Normal file
View File

@ -0,0 +1,7 @@
package main
import "templ-tests/app/router"
func main() {
router.Serve()
}

70
app/router/helpers.go Normal file
View File

@ -0,0 +1,70 @@
package router
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func isError(c *gin.Context, err error) bool {
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"details": err.Error(),
})
return true
}
return false
}
func raiseError(c *gin.Context, errCode int, message string) {
c.AbortWithStatusJSON(errCode, gin.H{
"details": message,
})
}
func raiseBadRequestError(c *gin.Context, message string) {
raiseError(c, http.StatusBadRequest, message)
}
func raiseNotFoundError(c *gin.Context, message string) {
raiseError(c, http.StatusNotFound, message)
}
func raiseInternalError(c *gin.Context, message string) {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"details": "Internal server error. We will we will fix it!",
})
}
func corsMiddleware() gin.HandlerFunc {
allowHeaders := [12]string{
"Content-Type",
"Content-Length",
"Accept-Encoding",
"X-CSRF-Token",
"Authorization",
"accept",
"origin",
"Cache-Control",
"X-Requested-With",
"x-timezone",
"Access-Control-Allow-Origin",
"Access-Control-Max-Age",
}
return func(c *gin.Context) {
allowOrigin := "*"
c.Writer.Header().Set("Access-Control-Allow-Origin", allowOrigin)
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", strings.Join(allowHeaders[:], ", "))
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}

34
app/router/router.go Normal file
View File

@ -0,0 +1,34 @@
package router
import (
"fmt"
"templ-tests/app/handlers"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
)
const (
APPHOST string = "0.0.0.0"
APPPORT int = 8000
STATIC_PATH string = "./static"
)
func initRouter() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
router.Use(corsMiddleware())
router.GET("/", handlers.Home)
router.Use(static.Serve("/static", static.LocalFile(STATIC_PATH, false)))
return router
}
func Serve() {
serverAddr := fmt.Sprintf("%s:%d", APPHOST, APPPORT)
fmt.Printf("Starting serving on %s\n", serverAddr)
router := initRouter()
router.Run(serverAddr)
}