Created
April 14, 2022 10:21
-
-
Save cdmatta/4b3066be7db23fe97294f4989c9c166c to your computer and use it in GitHub Desktop.
Gin, Golang, Embed FE host at / and backend at /api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"embed" | |
"fmt" | |
"io/fs" | |
"net/http" | |
"strings" | |
"github.com/gin-gonic/gin" | |
) | |
//go:embed frontend/build | |
var content embed.FS | |
func staticFilesEngine() *gin.Engine { | |
fsys := fs.FS(content) | |
contentStatic, _ := fs.Sub(fsys, "frontend/build") | |
eng := gin.New() | |
eng.Use(gin.Recovery()) | |
eng.StaticFS("/", http.FS(contentStatic)) | |
return eng | |
} | |
func apiEngine() *gin.Engine { | |
eng := gin.New() | |
eng.Use(gin.Recovery()) | |
apiG := eng.Group("/api") | |
{ | |
apiG.GET("/ping", func(c *gin.Context) { | |
c.String(http.StatusOK, "pong") | |
}) | |
} | |
return eng | |
} | |
func setupRouter() *gin.Engine { | |
api := apiEngine() | |
static := staticFilesEngine() | |
r := gin.New() | |
r.SetTrustedProxies([]string{"0.0.0.0"}) | |
r.Use(gin.Recovery()) | |
r.Any("/*any", func(c *gin.Context) { | |
path := c.Param("any") | |
if strings.HasPrefix(path, "/api") { | |
api.HandleContext(c) | |
} else if c.Request.Method == http.MethodGet { | |
static.HandleContext(c) | |
} | |
}) | |
return r | |
} | |
func main() { | |
r := setupRouter() | |
// Listen and Server on 0.0.0.0:8080 | |
r.Run(fmt.Sprint(":8080")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment