Use golang serve the static file embedded to binary file
The golang code to embed file to compile file
use the annotatioins to embed folder, this should embed current public
folder to binary file
1
2import (
3 "embed"
4 "fmt"
5 "os"
6 "io/fs"
7 "net/http"
8 "os/signal"
9 "runtime"
10 "strings"
11 "syscall"
12)
13
14
15//go:embed public
16var staticFiles embed.FS
17
18
19func main() {
20 public, _ := fs.Sub(staticFiles, "public")
21 // handle static files include HTML, CSS and JavaScripts.
22 http.Handle("/", http.FileServer(http.FS(public)))
23
24 go func() {
25 err = http.ListenAndServe("127.0.0.1:3000", nil)
26 if err != nil {
27 fmt.Println("Cant start server:", err)
28 os.Exit(1)
29 }
30 }()
31 handleSignals()
32}
33
34// handleSignals handle kill signal.
35func handleSignals() {
36 c := make(chan os.Signal, 1)
37 signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
38 <-c
39}
if use fiber framework can also to do this
- the
static.go
in web frontend folder, the frontend code should compile toui
folder
1package frontend
2
3import "embed"
4
5var (
6 //go:embed ui
7 FileSystem embed.FS
8)
9
10const (
11 RootPath = "ui"
12 IndexPath = RootPath + "/index.html"
13)
- the
vue.config.js
file definition
1const { defineConfig } = require('@vue/cli-service')
2module.exports = defineConfig({
3 transpileDependencies: true,
4 // configureWebpack: {
5 // devtool: 'inline-source-map'
6 // },
7 filenameHashing: false,
8 productionSourceMap: false,
9 outputDir: '../ui',
10 publicPath: '/',
11})
- serve the frontend golang code
1package api
2
3import (
4 "fmt"
5 "io/fs"
6 "net/http"
7 static "example/frontend"
8 "github.com/gofiber/fiber/v2"
9 fiberfs "github.com/gofiber/fiber/v2/middleware/filesystem"
10)
11
12
13func createRoute() {
14 app := fiber.New(fiber.Config{
15 ErrorHandler: func(c *fiber.Ctx, err error) error {
16 log.Warn().Msgf("[api.ErrorHandler] %s", err.Error())
17 return c.Status(fiber.StatusInternalServerError).JSON(GlobalErrorHandlerResp{
18 Success: false,
19 Message: err.Error(),
20 })
21 },
22 DisableStartupMessage: true,
23 })
24 staticFileSystem, err := fs.Sub(static.FileSystem, static.RootPath)
25 if err != nil {
26 panic(err)
27 }
28
29 app.Use("/", fiberfs.New(fiberfs.Config{
30 Root: http.FS(staticFileSystem),
31 Index: "index.html",
32 Browse: true,
33 }))
34}