reactjsgoreact-router-domgo-echo

I want to Serve React App with react router dom with echo


I want to Serve React App with react router dom with echo in Go. But I'm facing a problem in routing because if I directly go to that route I get not found error

package main

import (
    "fmt"
    checkerror "server/checkError"
    connectdb "server/connectDB"
    "server/handler"

    "github.com/gofor-little/env"
    echo "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
    _ "github.com/lib/pq"
)

func main() {
    err := env.Load(".env")
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    userDB := connectdb.UserDB{Name: "Hi", DBP: nil}
    err = userDB.ConnectDB()
    fmt.Println(userDB.DBP)
    checkerror.Checkerror(err)
    e := echo.New()
    e.Static("/","build")
    e.Use(middleware.Logger())
    handler.Apihandler(e, userDB.DBP)
    e.File("/","index.html")
    
    e.Logger.Fatal(e.Start(":1323"))
    
    defer func() {
        fmt.Println("DB disconnected")
        userDB.CloseDB()
    }()
}

This is code to serve the app Please help

I want to get access of routes from react


Solution

  • Instead of serving static files using static use the middleware of StaticWith config so it can redirect to index.HTML if route is not found

    e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
        Skipper: nil,
        // Root directory from where the static content is served.
        Root: "build",
        // Index file for serving a directory.
        // Optional. Default value "index.html".
        Index: "index.html",
        // Enable HTML5 mode by forwarding all not-found requests to root so that
        // SPA (single-page application) can handle the routing.
        HTML5:      true,
        Browse:     false,
        IgnoreBase: false,
        Filesystem: nil,
    }))