1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2025-02-07 14:40:16 +00:00
mycorrhiza/util/util.go

82 lines
2.2 KiB
Go
Raw Normal View History

package util
import (
2020-11-14 15:39:18 +05:00
"crypto/rand"
"encoding/hex"
2020-08-31 22:52:26 +05:00
"net/http"
"regexp"
"strings"
)
2020-10-25 20:06:51 +05:00
var (
URL string
ServerPort string
HomePage string
SiteNavIcon string
SiteName string
WikiDir string
2021-01-23 21:37:29 +05:00
UserHypha string
2021-01-24 00:00:58 +05:00
HeaderLinksHypha string
AuthMethod string
FixedCredentialsPath string
2020-10-25 20:06:51 +05:00
)
// ShorterPath is used by handlerList to display shorter path to the files. It simply strips WikiDir.
func ShorterPath(path string) string {
if strings.HasPrefix(path, WikiDir) {
tmp := strings.TrimPrefix(path, WikiDir)
if tmp == "" {
return ""
}
return tmp[1:]
}
return path
}
2020-08-31 22:52:26 +05:00
// HTTP200Page wraps some frequently used things for successful 200 responses.
func HTTP200Page(w http.ResponseWriter, page string) {
w.Header().Set("Content-Type", "text/html;charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(page))
}
2020-10-03 21:56:56 +05:00
// FindSubhyphae finds names of existing hyphae given the `hyphaIterator`.
func FindSubhyphae(hyphaName string, hyphaIterator func(func(string))) []string {
subhyphae := make([]string, 0)
hyphaIterator(func(otherHyphaName string) {
if strings.HasPrefix(otherHyphaName, hyphaName+"/") {
subhyphae = append(subhyphae, otherHyphaName)
}
})
return subhyphae
}
2020-11-14 15:39:18 +05:00
func RandomString(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
2021-01-10 16:58:02 +05:00
// Strip hypha name from all ancestor names, replace _ with spaces, title case
func BeautifulName(uglyName string) string {
2021-01-11 21:13:41 +05:00
if uglyName == "" {
return uglyName
}
2021-01-14 16:39:54 +05:00
return strings.Title(strings.ReplaceAll(uglyName, "_", " "))
2021-01-10 16:58:02 +05:00
}
// CanonicalName makes sure the `name` is canonical. A name is canonical if it is lowercase and all spaces are replaced with underscores.
func CanonicalName(name string) string {
return strings.ToLower(strings.ReplaceAll(name, " ", "_"))
}
// HyphaPattern is a pattern which all hyphae must match.
var HyphaPattern = regexp.MustCompile(`[^?!:#@><*|"\'&%{}]+`)
// IsCanonicalName checks if the `name` is canonical.
func IsCanonicalName(name string) bool {
return HyphaPattern.MatchString(name)
}