feat: add config

This commit is contained in:
Louis Dalibard 2024-04-27 12:40:07 +02:00
parent 8d9b91a097
commit 92a06925ca
5 changed files with 46 additions and 9 deletions

6
config.json Normal file
View File

@ -0,0 +1,6 @@
{
"host": ":3125",
"servedirs": {
"leech": "/home/ontake/Dev/go/leech"
}
}

View File

@ -1,7 +1,37 @@
package config
var Host = ":3125"
import (
"encoding/json"
"log"
"os"
"path/filepath"
)
var ServeDirs = map[string]string{
"leech": "/home/ontake/Dev/go/leech",
type ConfigS struct {
Host string `json:"host"`
ServeDirs map[string]string `json:"servedirs"`
}
var Config ConfigS
func Init() {
chosenConfigPath := "/etc/leech/"
// Deal with a JSON configuration file in that folder.
configFile := filepath.Join(chosenConfigPath, "config.json")
// Does the file not exist?
if _, err := os.Stat(configFile); os.IsNotExist(err) {
log.Fatal("config file couldn't be found")
} else {
// Load the existing file.
fh, err := os.Open(configFile)
if err != nil {
panic(err)
}
defer fh.Close()
decoder := json.NewDecoder(fh)
decoder.Decode(&Config)
}
}

BIN
leech

Binary file not shown.

View File

@ -15,6 +15,7 @@ import (
var assetsEmbed embed.FS
func main() {
config.Init()
app := fiber.New()
app.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
@ -28,9 +29,9 @@ func main() {
Browse: true,
}))
for dirName, dirToServe := range config.ServeDirs {
for dirName, dirToServe := range config.Config.ServeDirs {
app.Static("/serve/"+dirName, dirToServe)
}
app.Listen(config.Host)
app.Listen(config.Config.Host)
}

View File

@ -16,15 +16,15 @@ func HandleList(c *fiber.Ctx) error {
req := c.Params("req")
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
if req == "" {
keys := make([]string, 0, len(config.ServeDirs))
for k := range config.ServeDirs {
keys := make([]string, 0, len(config.Config.ServeDirs))
for k := range config.Config.ServeDirs {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return i < j
})
entries := make([]html.Entry, 0, len(config.ServeDirs))
entries := make([]html.Entry, 0, len(config.Config.ServeDirs))
for _, key := range keys {
entries = append(entries, html.Entry{
Name: key,
@ -36,7 +36,7 @@ func HandleList(c *fiber.Ctx) error {
return c.SendString(html.FileListPage(req, entries))
} else {
pathSlice := strings.Split(req, ".")
pathBase, ok := config.ServeDirs[pathSlice[0]]
pathBase, ok := config.Config.ServeDirs[pathSlice[0]]
if ok {
pathSlice[0] = pathBase
completePath := path.Join(pathSlice...)