mirror of
https://github.com/prymitive/karma
synced 2026-05-07 03:26:52 +00:00
There are a few config keys that needs to be passed to ui code before react app starts, we'll render them in the index.html as template
98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"html/template"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
assetfs "github.com/elazarl/go-bindata-assetfs"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type binaryFileSystem struct {
|
|
fs http.FileSystem
|
|
}
|
|
|
|
func (b *binaryFileSystem) Open(name string) (http.File, error) {
|
|
return b.fs.Open(name)
|
|
}
|
|
|
|
func (b *binaryFileSystem) Exists(prefix string, filepath string) bool {
|
|
if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
|
|
if _, err := b.fs.Open(p); err != nil {
|
|
// file does not exist
|
|
return false
|
|
}
|
|
// file exist
|
|
return true
|
|
}
|
|
// file path doesn't start with fs prefix, so this file isn't stored here
|
|
return false
|
|
}
|
|
|
|
func newBinaryFileSystem(root string) *binaryFileSystem {
|
|
fs := &assetfs.AssetFS{
|
|
Asset: Asset,
|
|
// Don't render directory index, return 404 for /static/ requests)
|
|
AssetDir: func(path string) ([]string, error) {
|
|
return nil, errors.New("Not found")
|
|
},
|
|
Prefix: root,
|
|
}
|
|
return &binaryFileSystem{fs}
|
|
}
|
|
|
|
// load a template from binary asset resource
|
|
func loadTemplate(t *template.Template, path string) *template.Template {
|
|
templateContent, err := Asset(path)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
var tmpl *template.Template
|
|
if t == nil {
|
|
// if template wasn't yet initialized do it here
|
|
t = template.New(path)
|
|
}
|
|
|
|
if path == t.Name() {
|
|
tmpl = t
|
|
} else {
|
|
// if we already have an instance of template.Template then
|
|
// add a new file to it
|
|
tmpl = t.New(path)
|
|
}
|
|
|
|
_, err = tmpl.Parse(string(templateContent))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
return nil
|
|
}
|
|
|
|
return t
|
|
}
|
|
|
|
func responseFromStaticFile(c *gin.Context, filepath string, contentType string) {
|
|
if !staticFileSystem.Exists("/", filepath) {
|
|
c.String(404, "Not found")
|
|
return
|
|
}
|
|
|
|
file, err := staticFileSystem.Open(filepath)
|
|
if err != nil {
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
buf := bytes.NewBuffer(nil)
|
|
_, err = buf.ReadFrom(file)
|
|
if err != nil {
|
|
c.AbortWithError(500, err)
|
|
return
|
|
}
|
|
c.Data(200, contentType, buf.Bytes())
|
|
}
|