DEV Community

ynwd
ynwd

Posted on

How to setup golang backend and react frontend in a monorepo

Previously, we have set up a frontend module using react and typescript in a monorepo.

Next, we will use the golang server to serve the built webapp.

.
├── go.mod
├── go.sum
├── main.go
├── package.json
└── web
    ├── components
    └── modules
        └── root
            ├── build
            │   ├── asset-manifest.json
            │   ├── favicon.ico
            │   ├── index.html
            │   ├── logo192.png
            │   ├── logo512.png
            │   ├── manifest.json
            │   ├── robots.txt
            │   └── static
            │       ├── css
            │       │   ├── main.33a5a96b.chunk.css
            │       │   └── main.33a5a96b.chunk.css.map
            │       └── js
            │           ├── 2.59f16c8b.chunk.js
            │           ├── 2.59f16c8b.chunk.js.LICENSE.txt
            │           ├── 2.59f16c8b.chunk.js.map
            │           ├── 3.93db3793.chunk.js
            │           ├── 3.93db3793.chunk.js.map
            │           ├── main.f7ff0158.chunk.js
            │           ├── main.f7ff0158.chunk.js.LICENSE.txt
            │           ├── main.f7ff0158.chunk.js.map
            │           ├── runtime-main.08d49f3a.js
            │           └── runtime-main.08d49f3a.js.map
            └── package.json


Enter fullscreen mode Exit fullscreen mode

clone repo: https://github.com/ynwd/monorepo/tree/typescript

create services folder

mkdir -p internal/services
Enter fullscreen mode Exit fullscreen mode

init golang app

go mod init github.com/ynwd/monorepo
Enter fullscreen mode Exit fullscreen mode

downlod fastrex package

go get github.com/fastrodev/fastrex
Enter fullscreen mode Exit fullscreen mode

this will generate go.mod file

module github.com/ynwd/monorepo

go 1.17

require github.com/fastrodev/fastrex v0.0.0-20211008073151-687f0b90ec18 // indirect

Enter fullscreen mode Exit fullscreen mode

create golang app entry point

/* main.go */
package main

import (
    "github.com/fastrodev/fastrex"
)

func main() {
    app := fastrex.New()
    app.Template("web/modules/root/build/index.html")
    app.Static("web/modules/root/build")
    app.Get("/", func(req fastrex.Request, res fastrex.Response) {
        err := res.Render()
        if err != nil {
            panic(err)
        }
    })
    err := app.Listen(8080)
    if err != nil {
        panic(err)
    }
}

Enter fullscreen mode Exit fullscreen mode

build react root module

npm run build -w @fstr/root
Enter fullscreen mode Exit fullscreen mode

run golang server

go run main.go
Enter fullscreen mode Exit fullscreen mode

You can see the final source code here: https://github.com/ynwd/monorepo/tree/fastrex

Discussion (0)