Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sundowndev
GitHub Repository: sundowndev/phoneinfoga
Path: blob/master/web/client.go
988 views
1
package web
2
3
import (
4
"embed"
5
"fmt"
6
"github.com/gin-gonic/gin"
7
"io/ioutil"
8
"mime"
9
"net/http"
10
"path"
11
"strings"
12
)
13
14
//go:embed client/dist/*
15
var clientFS embed.FS
16
17
const (
18
staticPath = "/"
19
)
20
21
func detectContentType(path string, data []byte) string {
22
arr := strings.Split(path, ".")
23
ext := arr[len(arr)-1]
24
25
if mimeType := mime.TypeByExtension(fmt.Sprintf(".%s", ext)); mimeType != "" {
26
return mimeType
27
}
28
29
return http.DetectContentType(data)
30
}
31
32
func walkEmbededClient(dir string, router *gin.Engine) error {
33
files, err := clientFS.ReadDir(dir)
34
if err != nil {
35
return err
36
}
37
for _, file := range files {
38
if file.IsDir() {
39
err := walkEmbededClient(path.Join(dir, file.Name()), router)
40
if err != nil {
41
return err
42
}
43
continue
44
}
45
46
assetPath := strings.ReplaceAll(path.Join(dir, file.Name()), "client/dist/", staticPath)
47
f, err := clientFS.Open(path.Join(dir, file.Name()))
48
if err != nil {
49
return err
50
}
51
data, err := ioutil.ReadAll(f)
52
if err != nil {
53
return err
54
}
55
56
if assetPath == staticPath+"index.html" {
57
assetPath = staticPath
58
}
59
60
router.GET(assetPath, func(c *gin.Context) {
61
c.Header("Content-Type", detectContentType(assetPath, data))
62
c.Writer.WriteHeader(http.StatusOK)
63
_, _ = c.Writer.Write(data)
64
c.Abort()
65
})
66
}
67
return nil
68
}
69
70
func registerClientRoutes(router *gin.Engine) error {
71
return walkEmbededClient("client/dist", router)
72
}
73
74