gonotes/internal/conf/conf.go

102 lines
2 KiB
Go
Raw Normal View History

package conf
import (
2025-06-25 22:43:34 +01:00
"embed"
2025-02-04 20:27:32 +00:00
"errors"
"io"
"log"
2025-02-04 20:27:32 +00:00
"net/http"
"os"
2025-06-01 21:27:08 +01:00
"path"
2025-02-04 20:27:32 +00:00
"path/filepath"
2025-01-28 22:08:01 +00:00
"github.com/pelletier/go-toml/v2"
)
2025-02-04 20:27:32 +00:00
type Asset struct {
Path string
Url string
}
2025-06-25 22:43:34 +01:00
func (asset *Asset) fetchIfNotExists(staticPath string) {
2025-02-04 20:27:32 +00:00
destPath := filepath.Join(staticPath, asset.Path)
2025-06-17 21:28:12 +01:00
err := os.MkdirAll(path.Dir(destPath), os.FileMode(0750))
2025-06-01 21:27:08 +01:00
if err != nil {
log.Printf("Couldn't create parent dirs of %s\n", destPath)
panic(err)
}
2025-02-04 20:27:32 +00:00
out, err := os.OpenFile(
destPath,
os.O_WRONLY|os.O_CREATE|os.O_EXCL,
0666,
)
if err != nil {
if errors.Is(err, os.ErrExist) {
log.Printf("%s already exists\n", destPath)
return
}
panic(err)
}
defer out.Close()
resp, err := http.Get(asset.Url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
panic(err)
}
}
type Config struct {
2025-07-30 09:35:01 +01:00
Address string
Protocol string
Extension string
NotesDir string
LogAccess bool
Production bool
}
2025-06-25 21:30:57 +01:00
var (
Conf Config
assets []Asset = []Asset{
2025-11-04 17:05:49 +00:00
{Path: "css/bootstrap.min.css", Url: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css"},
{Path: "js/bootstrap.bundle.min.js", Url: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"},
{Path: "css/easy-mde.min.css", Url: "https://unpkg.com/easymde/dist/easymde.min.css"},
{Path: "js/easy-mde.min.js", Url: "https://unpkg.com/easymde/dist/easymde.min.js"},
2025-06-25 21:30:57 +01:00
{Path: "icons/eye.svg", Url: "https://raw.githubusercontent.com/twbs/icons/refs/heads/main/icons/eye.svg"},
}
BaseTemplate string = "base.tmpl.html"
2025-06-26 21:22:30 +01:00
//go:embed static/*
2025-06-25 22:43:34 +01:00
Static embed.FS
//go:embed templates/*
Templates embed.FS
2025-06-25 21:30:57 +01:00
)
func LoadConfig(path string) {
var err error
b, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
err = toml.Unmarshal([]byte(b), &Conf)
if err != nil {
log.Fatal(err)
}
log.Printf("Config is %+v", Conf)
2025-06-25 22:43:34 +01:00
}
2025-02-04 20:27:32 +00:00
2025-06-25 22:43:34 +01:00
func FetchAssets() {
2025-06-25 21:30:57 +01:00
for _, asset := range assets {
2025-06-25 22:43:34 +01:00
asset.fetchIfNotExists("./internal/conf/static")
2025-02-04 20:27:32 +00:00
}
}