forked from struckchure/gv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
127 lines (100 loc) · 2.14 KB
/
server.go
File metadata and controls
127 lines (100 loc) · 2.14 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package gv
import (
"errors"
"fmt"
"log"
"os"
"github.com/evanw/esbuild/pkg/api"
"github.com/fatih/color"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
)
type Server struct {
e *echo.Echo
cfg ServerConfig
}
func (s *Server) Watch() error {
ctx, esErr := api.Context(s.cfg.EsBuildOptions)
if esErr != nil {
return esErr
}
if err := ctx.Watch(api.WatchOptions{}); err != nil {
return err
}
err := s.HandleHMR()
if err != nil {
return err
}
return nil
}
func (s *Server) Build() error {
ctx, esErr := api.Context(s.cfg.EsBuildOptions)
if esErr != nil {
return esErr
}
res := ctx.Rebuild()
if len(res.Errors) > 0 {
return errors.New(res.Errors[0].Text)
}
return nil
}
func (s *Server) Server() *echo.Echo {
return s.e
}
var HmrClientBroadcast = make(chan HmrResult)
func (s *Server) HandleHMR() error {
color.Magenta("[HMR] Wating for client to connect ...")
var upgrader = websocket.Upgrader{}
handler := func(c echo.Context) error {
// Upgrade connection to WebSocket
ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return err
}
defer ws.Close()
color.Green("[HMR] Client connected")
for {
for payload := range HmrClientBroadcast {
if err := ws.WriteJSON(payload); err != nil {
c.Logger().Error("WebSocket broadcast error:", err)
continue
}
}
}
}
s.e.GET("/__hmr__", handler)
return nil
}
func (s *Server) Start() error {
mode := os.Getenv("GV_MODE")
switch mode {
case "dev":
s.Watch()
case "build":
if err := s.Build(); err != nil {
log.Fatal(err)
}
return nil
}
fmt.Println("\n" + color.GreenString("➜") + " Local: " + color.MagentaString(fmt.Sprintf("http://%s:%d", s.cfg.Host, s.cfg.Port)) + "\n")
return s.e.Start(fmt.Sprintf("%s:%d", s.cfg.Host, s.cfg.Port))
}
type ServerConfig struct {
Host string
Port int
EsBuildOptions api.BuildOptions
WatchPath *string
WatchExcludePaths *[]string
}
func NewServer(cfg ServerConfig) *Server {
if os.Getenv("GV_MODE") == "" {
os.Setenv("GV_MODE", "dev")
}
e := echo.New()
e.HideBanner = true
e.HidePort = true
return &Server{
e: e,
cfg: cfg,
}
}