Many times we need to serve a webapp in a Golang app, but also sometimes we are using vite to handle the routes in the client, by that, we need to know how we can serve them easily without a nginx server by using Golang.
With what webapp works? With every app that is built with javascript
We need to get using golang first, you can download it by clicking here, and then you install it, you need to go in your terminal where you have the frontend app, create a folder for the backend, in this example will be... backend hehe, and run:
1cd backend && go mod init github.com/<your_username>/<your_repo_name>
Note: change your_username and your_repo_name by your personal data
Note 2: for powershell users, change &&
with semicolon
After that, lets create the main.go file
1cd backend && touch main.go
1// main.go
2package main
3
4import (
5 "log"
6 "net/http"
7 "path"
8)
9
10func main() {
11 // Here is where the frontend build lives
12 // make sure that you have the dist folder were your builf files are
13 fs := http.FileServer(http.Dir("./dist"))
14
15 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
16 // serves the specified file
17 filePath := path.Join("./dist", r.URL.Path)
18
19 // checks if the file exists
20 _, err := http.Stat(filePath)
21 if err == nil {
22 fs.ServeHTTP(w, r)
23 return
24 }
25
26 // if the file doesn't exists (ex. is a frontend route), serves index.html
27 http.ServeFile(w, r, "./dist/index.html")
28 })
29
30 log.Println("Server started at http://localhost:8080")
31 log.Fatal(http.ListenAndServe(":8080", nil))
32}
33
With this, in your frontend project you need to make the build, if you're using vite, put this in the vite config
1import { defineConfig } from "vite";
2
3// https://vitejs.dev/config/
4export default defineConfig({
5 // ...
6 build: {
7 outDir: "../backend/dist",
8 emptyOutDir: true,
9 },
10 // ...
11});
Only we need to run the app, if you want to test, run:
1cd backend && go run .
Or, if you want to make the build first:
1cd backend && go build -o server .
After that you'll be able to run it calling ./server
, remember if you are in windows put the .exe extension
Happy coding!