forked from tamilpp25/Iridium-SR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
frontend_server.go
90 lines (76 loc) · 1.6 KB
/
frontend_server.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
88
89
90
package main
import (
"embed"
"io"
"io/fs"
"log"
"net/http"
"os"
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
)
var eventStream = make(chan string)
//go:embed frontend/public
var staticFolder embed.FS
func startServer() {
r := gin.Default()
r.GET("/api/start", apiStart)
r.GET("/api/stop", apiStop)
r.POST("/api/upload", apiUpload)
r.GET("/api/stream", stream)
r.Use(static.Serve("/", EmbedFolder(staticFolder, "frontend/public")))
defer close(eventStream)
err := r.Run(":1984")
if err != nil {
log.Fatalln("Could not start http server", err)
}
}
func apiStart(c *gin.Context) {
go openCapture()
}
func apiStop(c *gin.Context) {
go closeHandle()
}
func apiUpload(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
log.Println("Could not handle upload file", err)
return
}
err = c.SaveUploadedFile(file, os.TempDir()+file.Filename)
if err != nil {
log.Println("Could not handle upload file", err)
return
}
go openPcap(os.TempDir() + file.Filename)
}
func stream(c *gin.Context) {
c.Stream(func(w io.Writer) bool {
c.SSEvent("packetNotify", <-eventStream)
return true
})
}
func sendStreamMsg(msg string) {
go func() {
eventStream <- msg
}()
}
type embedFileSystem struct {
http.FileSystem
}
func (e embedFileSystem) Exists(prefix string, path string) bool {
_, err := e.Open(path)
if err != nil {
return false
}
return true
}
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),
}
}