Skip to content

Instantly share code, notes, and snippets.

@AEROGU
Created February 6, 2023 06:53
Show Gist options
  • Save AEROGU/43eb22843d6e89f82420045f3ca6ce0b to your computer and use it in GitHub Desktop.
Save AEROGU/43eb22843d6e89f82420045f3ca6ce0b to your computer and use it in GitHub Desktop.
GO & Gin: Use the same gin router to mount embedded frontend and your API routes
package main
/*
Uses the same gin router to mount embedded frontend.
Change the //go:embed .\frontend
Change the `root, _ := fs.Sub(embedFrontendFS, "frontend")`
*/
import (
"embed"
"io/fs"
"net/http"
"github.com/gin-gonic/gin"
)
var (
//go:embed .\frontend
embedFrontendFS embed.FS
)
func embedFrontend(router *gin.Engine, httpPrefix string) {
// This works only if mounted on a subroute like "/static"
// if mounted in "/" there will be conflicts with your "/api/*"
// root, _ := fs.Sub(embedFrontendFS, "frontend")
// router.StaticFS("/static", http.FS(root))
// This second approach works just fine
root, _ := fs.Sub(embedFrontendFS, "frontend") // Set root folder inside embed tree
fileserver := http.FileServer(http.FS(root))
fileserver = http.StripPrefix(httpPrefix, fileserver)
router.Use(func(c *gin.Context) {
fileserver.ServeHTTP(c.Writer, c.Request)
c.Abort()
})
}
package main
import (
"myProject/controllers"
"myProject/initializers"
"myProject/models"
"log"
"os"
"github.com/gin-gonic/gin"
)
func init() { // GO built-in function, executed on package import, just before `main`
initializers.LoadEnvVars()
gin.SetMode(os.Getenv("GIN_MODE"))
}
func main() {
db := initializers.NewDbConnection()
if os.Getenv("GORM_LOG_ALL_QUERYS") == "true" {
db = db.Debug() // Log out ALL SQL querryes
}
controllers.SetDBConnection(db)
models.SetDBConnection(db)
router := gin.Default()
setupRoutes(router) // API routes
embedFrontend(router, "/") // File server Routes <-- THIS IS WHAT YOU ARE LOOKING FOR
go router.Run() // Start server in a separate thread
ConsoleLoop() // Use my commands in console while server is runnung
log.Println("🖥️ Servidor de reportes detenido.\nBye.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment