1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-12-12 05:20:26 +00:00

Create a package for config

This commit is contained in:
Timur Ismagilov 2020-06-23 22:53:05 +05:00
parent 279a14cb07
commit 962ace319a
11 changed files with 112 additions and 43 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
hypha

75
cfg/config.go Normal file
View File

@ -0,0 +1,75 @@
package cfg
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"path/filepath"
)
var (
WikiDir string
TemplatesDir string
configJsonPath string
// Default values that can be overriden in config.json
Address = "127.0.0.1:80"
TitleEditTemplate = `Edit %s`
TitleTemplate = `%s`
GenericErrorMsg = `<b>Sorry, something went wrong</b>`
DefaultTitle = "MycorrhizaWiki"
DefaultHeaderText = `MycorrhizaWiki 🍄`
DefaultFooterText = `This website runs <a href="https://github.com/bouncepaw/mycorrhiza">MycorrhizaWiki</a>.`
DefaultSidebar = ""
DefaultBodyBottom = ""
DefaultContent = "It is empty here"
DefaultStyles = `
<link rel="stylesheet" href="/sys/main.css?action=raw">
`
)
func InitConfig(wd string) bool {
log.Println("WikiDir is", wd)
WikiDir = wd
TemplatesDir = filepath.Join(filepath.Dir(WikiDir), "templates")
configJsonPath = filepath.Join(filepath.Dir(WikiDir), "config.json")
if _, err := os.Stat(configJsonPath); os.IsNotExist(err) {
log.Println("config.json not found, using default values")
} else {
log.Println("config.json found, overriding default values...")
return readConfig()
}
return true
}
func readConfig() bool {
configJsonContents, err := ioutil.ReadFile(configJsonPath)
if err != nil {
log.Fatal("Error when reading config.json:", err)
return false
}
cfg := struct {
Address string `json:"address"`
TitleTemplates struct {
EditHypha string `json:"edit-hypha"`
ViewHypha string `json:"view-hypha"`
} `json:"title-templates"`
}{}
err = json.Unmarshal(configJsonContents, &cfg)
if err != nil {
log.Fatal("Error when parsing config.json:", err)
return false
}
Address = cfg.Address
TitleEditTemplate = cfg.TitleTemplates.EditHypha
TitleTemplate = cfg.TitleTemplates.ViewHypha
return true
}

View File

@ -1,16 +0,0 @@
package main
const (
TitleEditTemplate = `Edit %s at MycorrhizaWiki`
TitleTemplate = `%s at MycorrhizaWiki`
DefaultTitle = "MycorrhizaWiki"
DefaultHeaderText = `MycorrhizaWiki 🍄`
DefaultFooterText = `This website runs <a href="https://github.com/bouncepaw/mycorrhiza">MycorrhizaWiki</a>.`
DefaultSidebar = ""
DefaultBodyBottom = ""
DefaultContent = "It is empty here"
DefaultStyles = `
<link rel="stylesheet" href="/sys/main.css?action=raw">
`
GenericErrorMsg = `<b>Sorry, something went wrong</b>`
)

View File

@ -9,6 +9,7 @@ import (
"strings"
"time"
"github.com/bouncepaw/mycorrhiza/cfg"
"github.com/gorilla/mux"
)
@ -95,7 +96,7 @@ func getHypha(name string) (*Hypha, bool) {
log.Println("Create hypha", name)
h := &Hypha{
FullName: name,
Path: filepath.Join(rootWikiDir, name),
Path: filepath.Join(cfg.WikiDir, name),
Revisions: make(map[string]*Revision),
parentName: filepath.Dir(name),
}
@ -177,7 +178,7 @@ func HandlerUpdate(w http.ResponseWriter, rq *http.Request) {
} else {
h = &Hypha{
FullName: vars["hypha"],
Path: filepath.Join(rootWikiDir, vars["hypha"]),
Path: filepath.Join(cfg.WikiDir, vars["hypha"]),
Revisions: make(map[string]*Revision),
parentName: filepath.Dir(vars["hypha"]),
}

View File

@ -10,6 +10,8 @@ import (
"path/filepath"
"strconv"
"strings"
"github.com/bouncepaw/mycorrhiza/cfg"
)
// `Hypha` represents a hypha. It is the thing MycorrhizaWiki generally serves.
@ -95,7 +97,7 @@ func ActionEdit(hyphaName string, w http.ResponseWriter) {
if err != nil {
log.Println("Could not read", newestRev.TextPath)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(GenericErrorMsg))
w.Write([]byte(cfg.GenericErrorMsg))
return
}
initContents = string(contents)

15
main.go
View File

@ -8,6 +8,7 @@ import (
"path/filepath"
"time"
"github.com/bouncepaw/mycorrhiza/cfg"
"github.com/gorilla/mux"
)
@ -36,10 +37,6 @@ func RevInMap(m map[string]string) string {
return "0"
}
// `rootWikiDir` is a directory where all wiki files reside.
// `templatesDir` is where templates are.
var rootWikiDir, templatesDir string
// `hyphae` is a map with all hyphae. Many functions use it.
var hyphae map[string]*Hypha
@ -47,17 +44,15 @@ func main() {
if len(os.Args) == 1 {
panic("Expected a root wiki pages directory")
}
// Required so the rootWikiDir hereinbefore does not get redefined.
var err error
rootWikiDir, err = filepath.Abs(os.Args[1])
wikiDir, err := filepath.Abs(os.Args[1])
if err != nil {
panic(err)
}
templatesDir = filepath.Join(filepath.Dir(rootWikiDir), "templates")
log.Println("Welcome to MycorrhizaWiki α")
cfg.InitConfig(wikiDir)
log.Println("Indexing hyphae...")
hyphae = recurFindHyphae(rootWikiDir)
hyphae = recurFindHyphae(wikiDir)
log.Println("Indexed", len(hyphae), "hyphae. Ready to accept requests.")
// Start server code. See handlers.go for handlers' implementations.
@ -123,7 +118,7 @@ func main() {
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8000",
Addr: cfg.Address,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,

BIN
mycorrhiza Executable file

Binary file not shown.

View File

@ -5,12 +5,14 @@ import (
"fmt"
"path"
"text/template"
"github.com/bouncepaw/mycorrhiza/cfg"
)
// EditHyphaPage returns HTML page of hypha editor.
func EditHyphaPage(name, textMime, content, tags string) string {
keys := map[string]string{
"Title": fmt.Sprintf(TitleEditTemplate, name),
"Title": fmt.Sprintf(cfg.TitleEditTemplate, name),
"Header": renderFromString(name, "Hypha/edit/header.html"),
}
page := map[string]string{
@ -34,14 +36,14 @@ func HyphaPage(rev Revision, content string) string {
// HyphaGeneric is used when building renderers for all types of hypha pages
func HyphaGeneric(name string, content, templatePath string) string {
sidebar := DefaultSidebar
sidebar := cfg.DefaultSidebar
if bside := renderFromMap(map[string]string{
"Tree": GetTree(name, true).AsHtml(),
}, "Hypha/view/sidebar.html"); bside != "" {
sidebar = bside
}
keys := map[string]string{
"Title": fmt.Sprintf(TitleTemplate, name),
"Title": fmt.Sprintf(cfg.TitleTemplate, name),
"Sidebar": sidebar,
}
return renderBase(renderFromString(content, templatePath), keys)
@ -53,13 +55,13 @@ func HyphaGeneric(name string, content, templatePath string) string {
// keys: map with replaced standart fields
func renderBase(content string, keys map[string]string) string {
page := map[string]string{
"Title": DefaultTitle,
"Head": DefaultStyles,
"Sidebar": DefaultSidebar,
"Main": DefaultContent,
"BodyBottom": DefaultBodyBottom,
"Header": renderFromString(DefaultHeaderText, "header.html"),
"Footer": renderFromString(DefaultFooterText, "footer.html"),
"Title": cfg.DefaultTitle,
"Head": cfg.DefaultStyles,
"Sidebar": cfg.DefaultSidebar,
"Main": cfg.DefaultContent,
"BodyBottom": cfg.DefaultBodyBottom,
"Header": renderFromString(cfg.DefaultHeaderText, "header.html"),
"Footer": renderFromString(cfg.DefaultFooterText, "footer.html"),
}
for key, val := range keys {
page[key] = val
@ -70,7 +72,7 @@ func renderBase(content string, keys map[string]string) string {
// renderFromMap applies `data` map to template in `templatePath` and returns the result.
func renderFromMap(data map[string]string, templatePath string) string {
filePath := path.Join(templatesDir, templatePath)
filePath := path.Join(cfg.TemplatesDir, templatePath)
tmpl, err := template.ParseFiles(filePath)
if err != nil {
return err.Error()
@ -84,7 +86,7 @@ func renderFromMap(data map[string]string, templatePath string) string {
// renderFromMap applies `data` string to template in `templatePath` and returns the result.
func renderFromString(data string, templatePath string) string {
filePath := path.Join(templatesDir, templatePath)
filePath := path.Join(cfg.TemplatesDir, templatePath)
tmpl, err := template.ParseFiles(filePath)
if err != nil {
return err.Error()

7
w/config.json Normal file
View File

@ -0,0 +1,7 @@
{
"address": "127.0.0.1:1737",
"title-templates": {
"edit-hypha": "Edit %s at MycorrhizaWiki",
"view-hypha": "%s at MycorrhizaWiki"
}
}

View File

Before

Width:  |  Height:  |  Size: 608 KiB

After

Width:  |  Height:  |  Size: 608 KiB

View File

@ -7,6 +7,8 @@ import (
"path/filepath"
"regexp"
"strconv"
"github.com/bouncepaw/mycorrhiza/cfg"
)
const (
@ -58,8 +60,8 @@ func scanHyphaDir(fullPath string) (valid bool, possibleSubhyphae []string, meta
// hyphaName gets name of a hypha by stripping path to the hypha in `fullPath`
func hyphaName(fullPath string) string {
// {rootWikiDir}/{the name}
return fullPath[len(rootWikiDir)+1:]
// {cfg.WikiDir}/{the name}
return fullPath[len(cfg.WikiDir)+1:]
}
// recurFindHyphae recursively searches for hyphae in passed directory path.