slovo

package
v0.0.0-...-f12796d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package slovo contains code for preparing and serving web pages for the site -- the front-end.

Index

Constants

View Source
const ANY = "ANY"

ANY is an aggregata for any http method.

View Source
const CODENAME = "U+2C16 GLAGOLITIC CAPITAL LETTER UKU (Ⱆ)"
View Source
const EXT = `(html?)`

EXT is a regular expression for the requested default format.

View Source
const LNG = `((?:[a-z]{2}-[a-z]{2})|[a-z]{2})`

LNG is a regular expression for language notation.

View Source
const QS = `(.*)?`

QS stands for QUERY_STRING - this is the rest of the URL. We match anything.

View Source
const SLOG = `([\pL\-_\d]{3,})`

SLOG is a regular expression capturing group to match what is possible to have between two slashes in an URL path. Used in RegexRules for rewriting urls for the Routes parser. At least three any unicode letter, dash or underscore. Note! REQUEST_URI is url-escaped at this time. We currently use Skipper to unnescape the raw RequestURI.

View Source
const VERSION = "2024.03.12-alpha-014"

Variables

This section is empty.

Functions

func BinDir

func BinDir() string

BinDir returns the directory where the binary resides. We assume that this is the root of the project.

func FileIsReadable

func FileIsReadable(path string) bool

func HomeDir

func HomeDir() string

HomeDir returns the slovo2 installation directory. This is the directory where we have the `domove` directory.

func PreferDomainStaticFiles

func PreferDomainStaticFiles(next echo.HandlerFunc) echo.HandlerFunc

PreferDomainStaticFiles serves static files from domain specific directories if these files exist.

func SlovoContext

func SlovoContext(next echo.HandlerFunc) echo.HandlerFunc

SlovoContext is a middleware function which instantiates slovo's custom context and executes some tasks common to all pages in the site. These are:

  • Context.BindArgs
  • renders (spits out) cached pages
  • sets the domain root c.DomainRoot after the current domain for this HTTP request.
  • modifies gledki.Gledki.TemplatesRoots so the first path is always defined by the current domain if the `domove` table record contains some value in its templates column. This way every domain can have it's own templates.
  • prepares some default items in gledki.Stash

func Start

func Start(logger *log.Logger)

Start starts Echo in server mode.

func StartCGI

func StartCGI(logger *log.Logger)

StartCGI starts Echo in CGI mode.

Types

type Binder

type Binder struct {
	*echo.DefaultBinder
}

Binder embeds echo.DefaultBinder TODO: Read whole https://go101.org/article/type-embedding.html

func (*Binder) Bind

func (b *Binder) Bind(args any, c echo.Context) (err error)

Bind binds some variables into a structure to be passed to queries for Stranici and Celini.

type Config

type Config struct {
	// Langs is a list of supported languages. The last is the default.
	Langs []string `yaml:"Langs"`
	Debug bool     `yaml:"Debug"`
	// DomoveRoot is the root folder for static content and templates of parked
	// domains. Defaults to `BinDir()/domove`.
	DomoveRoot string `yaml:"DomoveRoot"`
	// DomovePrefixes is a common list of prefixes, used in parked domains to
	// create subdomains for various purposes. These prefixes are cut and then
	// the domain name is used for domain root.
	DomovePrefixes []string `yaml:DomovePrefixes`
	// GuestID is the id of the user when a guest (unauthenticated) visits the
	// site.
	GuestID int32 `yaml:"GuestID"`
	// File is the path to the configuration file in which this structure will
	// be dumped in YAML format.
	File     string   `yaml:"File"`
	Serve    Serve    `yaml:"Serve"`
	StartCGI ServeCGI `yaml:"ServeCGI"`
	// List of routes to be created by Echo
	Routes Routes `yaml:"Routes"`
	// Arguments for instantiating GledkiRenderer
	Renderer Renderer `yaml:"Renderer"`
	// StaticRoutes - folders` routes to be served by `echo` from
	// within the installation public folder. Common for all domains. If a
	// file is not found in the domain public folder, it will fall back to
	// be served from here if found. For example request to /css/site.css
	// will be served from public/css/site.css.
	// `e.Static("/css","public/css").`
	StaticRoutes []StaticRoute `yaml:"StaticRoutes"`
	// DomoveStaticFiles is a regex of file extensions. If a file, matching the
	// regex is requested, we will look into the domain specific public folder
	// and serve it if found.
	DomoveStaticFiles string `yaml:DomoveStaticFiles`
	// DB is for database configuration. For now we use sqlite3.
	DB DBConfig `yaml:"DB"`
	// Rewrite is used to pass configuration values to
	// [middleware.RewriteWithConfig].
	Rewrite Rewrite `yaml:"Rewrite"`
	// CachePages - should we cache pages or not. true means `yes` and false
	// means `no`
	CachePages bool `yaml:"CachePages"`
}

Config is the root structure of the configuration for slovo. We preserve the case and style of each node and scalar item between YAML file and Go source code for best recognition.

var Cfg Config

Cfg is the global configuration structure for slovo. The default is hardcodded and it can be dumped to YAML by using the command `slovo2 config dump`. To read automatically the YAML file on startup, the SLOVO_CONFIG environment variable must be set to the config file path.

type Context

type Context struct {
	echo.Context
	// StraniciArgs contains a pointer to [m.StraniciArgs].
	StraniciArgs *m.StraniciArgs

	// DomainRoot is the root folder for static content folders and `templates`
	// folder of the domain for this HTTP request.
	DomainRoot string
	// Domain contains a pointer to a m.Domove record - the current domain.
	Domain *m.Domove
	// contains filtered or unexported fields
}

Context is our custom context. It extends echo.Context. To use it in our handlers, we have to cast echo.Context to slovo.Context. Here is a full example.

func celiniExecute(ec echo.Context) error {
	c := ec.(*Context)
	log := c.Logger()
	cel := new(model.Celini)
	if err := cel.FindForDisplay(*c.StraniciArgs); err != nil {
		log.Errorf("celina: %#v; error:%w; ErrType: %T; args: %#v", cel, err, err, c.StraniciArgs)
		return handleNotFound(c, err)
	}
	return c.Render(http.StatusOK, cel.TemplatePath("celini/note"), buildCeliniStash(c, cel))
}

func (*Context) BindArgs

func (c *Context) BindArgs() (*m.StraniciArgs, error)

BindArgs prepares common arguments for `stranici` and `celini`. It is idempotent. If invoked multiple times within a request, it returns the same prepared model.StraniciArgs.

func (*Context) CanonicalPath

func (c *Context) CanonicalPath() string

CanonicalPath returns the canonical URL for the current page.

func (*Context) DB

func (c *Context) DB() *sqlx.DB

type DBConfig

type DBConfig struct {
	DSN string `yaml:"DSN"`
}

type EchoRenderer

type EchoRenderer struct {
	*gledki.Gledki
}

func GledkiMust

func GledkiMust(roots []string, ext string, tags [2]string, loadFiles bool, logger gledki.Logger) *EchoRenderer

func (*EchoRenderer) Render

func (g *EchoRenderer) Render(w io.Writer, name string, data any, c echo.Context) error

Render abides to the echo.Echo interface for echo.Renderer, but expects the template data to be of type gledki.Stash which actually is map[string]any.

type Renderer

type Renderer struct {
	TemplateRoots []string  `yaml:"TemplateRoots"`
	Ext           string    `yaml:"Ext"`
	Tags          [2]string `yaml:"Tags"`
	LoadFiles     bool      `yaml:"LoadFiles"`
}

Renderer contains arguments, passed to GledkiMust.

type Rewrite

type Rewrite struct {
	SkipperFuncName string `yaml:"SkipperFuncName"`
	// Rules is a map of string to string in which the key is a regular
	// expression and the value is the resulting route mapping description
	Rules map[string]string `yaml:"Rules"`
}

Rewrite is used to pass configuration values to middleware.RewriteWithConfig.

func (Rewrite) ToRewriteRules

func (rc Rewrite) ToRewriteRules() (rewriteConfig middleware.RewriteConfig)

ToRewriteRules converts slovo.Rewrite to middleware.RewriteConfig structure, suitable for passing to middleware.RewriteWithConfig and returns it. Particularly SkipperFuncName is converted to middleware.RewriteConfig.Skipper and Rules are converted to middleware.RewriteConfig.RegexRules. This is somehow easier than implementing MarshalYAML and UnmarshalYAML.

type Route

type Route struct {
	// Method is a method name from echo.Echo.
	Method string `yaml:"Method"`
	// Handler stores a HTTP handler function name as string.
	// It is not possible to lookup a function by its name (as a string) in Go,
	// but we need to store the function names in the configuration file to
	// easily enable/disable a route. So we use a map in slovo/handlers.go `var
	// handlers = map[string]func(c echo.Context) error`
	Handler string `yaml:"Handler"`
	// Path is the REQUEST_PATH
	Path string `yaml:"Path"`
	// MiddlewareFuncs is optional
	MiddlewareFuncs []string `yaml:"MiddlewareFunc"`
	// Name is the name of the route. Used to generate URIs. See
	// https://echo.labstack.com/docs/routing#route-naming
	Name string `yaml:"Name"`
}

type Routes

type Routes []Route

type Serve

type Serve struct {
	// Location is descrived as f.q.d.n:port
	Location string `yaml:"Location"`
}

Serve has configuration properties, passed to slovo.Start.

type ServeCGI

type ServeCGI struct {
	HTTP_HOST      string `yaml:"HTTP_HOST"`
	REQUEST_URI    string `yaml:"REQUEST_URI"`
	REQUEST_METHOD string `yaml:"REQUEST_METHOD"`
	// SERVER_PROTOCOL used in CGI environment - HTTP/1.1. Recuired variable by
	// the cgi Go module.
	SERVER_PROTOCOL     string `yaml:"SERVER_PROTOCOL"`
	HTTP_ACCEPT_CHARSET string `yaml:"HTTP_ACCEPT_CHARSET"`
	CONTENT_TYPE        string `yaml:"CONTENT_TYPE"`
}

ServeCGI contains minimum ENV values for emulating a CGI request on the command line. All of these can be overridden via flags. See https://www.rfc-editor.org/rfc/rfc3875

type Stash

type Stash = gledki.Stash

type StaticRoute

type StaticRoute struct {
	Prefix string `yaml:"Prefix"`
	Root   string `yaml:"Root"`
}

StaticRoute describes a file path which will be served by echo.

type StaticRoutes

type StaticRoutes []StaticRoute

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL