-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (70 loc) · 1.86 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"embed"
"flag"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/fullstack-lang/gonggooglecharts/go/controllers"
"github.com/fullstack-lang/gonggooglecharts/go/orm"
)
var (
logDBFlag = flag.Bool("logDB", false, "log mode for db")
logGINFlag = flag.Bool("logGIN", false, "log mode for gin")
apiFlag = flag.Bool("api", false, "it true, use api controllers instead of default controllers")
)
func main() {
log.SetPrefix("gonggooglecharts: ")
log.SetFlags(0)
// parse program arguments
flag.Parse()
// setup controlers
if !*logGINFlag {
myfile, _ := os.Create("/tmp/server.log")
gin.DefaultWriter = myfile
}
r := gin.Default()
r.Use(cors.Default())
// setup GORM
db := orm.SetupModels(*logDBFlag, "./test.db")
// mandatory, otherwise, bizarre errors occurs
db.DB().SetMaxOpenConns(1)
// Provide db variable to controllers
r.Use(func(c *gin.Context) {
c.Set("db", db) // a gin Context can have a map of variable that is set up at runtime
c.Next()
})
controllers.RegisterControllers(r)
// provide the static route for the angular pages
r.Use(static.Serve("/", EmbedFolder(ng, "ng/dist/ng")))
r.NoRoute(func(c *gin.Context) {
fmt.Println(c.Request.URL.Path, "doesn't exists, redirect on /")
c.Redirect(http.StatusMovedPermanently, "/")
c.Abort()
})
log.Printf("Server ready to serve on localhost:8080")
r.Run()
}
//go:embed ng/dist/ng
var ng embed.FS
type embedFileSystem struct {
http.FileSystem
}
func (e embedFileSystem) Exists(prefix string, path string) bool {
_, err := e.Open(path)
return err == nil
}
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
fsys, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return embedFileSystem{
FileSystem: http.FS(fsys),
}
}