Go

[Go][gin] 리액트 정적 파일 서빙

_HelloWorld_ 2025. 2. 15. 12:14
package main

import (
	"net/http"

	"github.com/gin-gonic/contrib/static"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	r.Use(static.Serve("/", static.LocalFile("./front/build", true)))

    // SPA Fallback
    r.NoRoute(func(c *gin.Context) {
        c.File("./front/dist/index.html")
    })

	api := r.Group("/api")
	{
		api.GET("/", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "pong",
			})
		})
	}

	r.NoRoute(func(c *gin.Context) {
			c.File("./front/build/index.html")
	})

	r.Run(":8080") // 서버 실행
}

리액트 앱을 빌드하면 build라는 폴더가 생김

 

해당 폴더 내에는 빌드 되고 난 파일들이 생기는데, 여기서에서 index.html 이라는 정적 파일을 gin에 서빙 시켜 

 

경로에 맞게 URL에 접근한다면 리액트 앱이 보이고, 

백엔드 URL 경로에 접근한다면 백엔드 결과물이 보이는 코드...