cfg

package
v0.0.0-...-f9eced6 Latest Latest
Warning

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

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

Documentation

Overview

Package cfg implements a configuration database, loaded from a json file. Filename must be given as command line argument or environment variable. Access to the config data is made in threadsafe manner.

Index

Constants

This section is empty.

Variables

View Source
var CfgPath = filepath.Join(".", "config.json")

CfgPath is obtained by ENV variable or command line flag in main package. Being set from the main package. Holds the relative path and filename to look for; could be "./cfg/config.json". Relative to the app main dir.

Functions

func Load

func Load(r io.Reader)

Load reads from an io.Reader to avoid cyclical deps.

To avoid concurrent access problems: No method to ConfigT, no pointer receiver. We could *copy* at the end of method *c = *newCfg, but onerous. Instead: cfgS = &tempCfg

Contains some validations.

func LoadFakeConfigForTests

func LoadFakeConfigForTests()

LoadFakeConfigForTests makes bootstrap overhead superfluous by creating a

func Pref

func Pref(pth ...string) string

Pref prefixes a URL path with an application dir prefix. Any URL Path is prefixed with the URLPathPrefix, if URLPathPrefix is set.

Prevents unnecessary slashes. No trailing slash Routes with trailing "/" such as "/path/" get a redirect "/path" => "/path/" if "/path" is not registered yet. This behavior of func server.go - (mux *ServeMux) Handle(...) is nasty since it depends on the ORDER of registrations.

Best strategy might be

mux.HandleFunc(appcfg.Pref(urlPath),   argFunc)   // Claim "/path"
mux.HandleFunc(appcfg.PrefTS(urlPath), argFunc)   // Claim "/path/"

Notice the order - other way around would block "/path" with a redirect handler

func PrefTS

func PrefTS(pth ...string) string

PrefTS is like Prefix(); TS stands for (with) trailing slash; useful for registering handlers so that /p1/p2/ also serves /p1/p2

func Stack

func Stack(base, addenum cssVars) cssVars

Stack combines / merges addenum into base

func SwitchToTestConfig

func SwitchToTestConfig()

SwitchToTestConfig is used to run systemtests on a different port without TLS.

func TrimPrefix

func TrimPrefix(url string) (ret string)

TrimPrefix removes the prefix from a URL

Types

type ConfigT

type ConfigT struct {
	IsProduction bool `json:"is_production"` // true => templates are not recompiled

	AppName       string `json:"app_name"`       // with case, i.e. 'Survey Server'; use localized trl.Map app_label, app_org
	URLPathPrefix string `json:"urlpath_prefix"` // lower case - no slashes, i.e. 'myapp'
	AppMnemonic   string `json:"app_mnemonic"`   // differentiation of static dirs - when URLPathPrefix is empty; imagine multiple instances

	LetsEncrypt bool   `json:"lets_encrypt"`
	HostName    string `json:"host_name"` // for ACME cert; i.e. survey2.zew.de

	BindHost               string `json:"bind_host"`                   // "0.0.0.0"
	BindSocket             int    `json:"bind_socket"`                 // 8081 or 80
	BindSocketFallbackHTTP int    `json:"bind_socket_fallback_http"`   // 8082
	BindSocketTests        int    `json:"bind_socket_tests,omitempty"` // another port for running test server, 8181
	TLS                    bool   `json:"tls"`
	TLS13                  bool   `json:"tls13"`                     // ultra safe - but excludes internet explorer 11
	ReadTimeOut            int    `json:"http_read_time_out"`        // limit large requests
	ReadHeaderTimeOut      int    `json:"http_header_read_time_out"` // limit request header time - then use per request restrictions r = r.WithContext(ctx) to limit - stackoverflow.com/questions/39946583
	WriteTimeOut           int    `json:"http_write_time_out"`       // for *responding* large files over slow networks, i.e. videos, set to 30 or 60 secs

	TimeOutUsual      int      `json:"time_out_usual,omitempty"`
	TimeOutExceptions []string `json:"time_out_exceptions,omitempty"`

	MaxPostSize int64 `json:"max_post_size,omitempty"` // request body size limit, against DOS attacks, limits file uploads

	// LocationName i.e. "Europe/Berlin", see Go\lib\time\zoneinfo.zip;
	// LocationName only serves for initializing Loc at application start
	// after that, application should use Loc
	LocationName   string         `json:"location,omitempty"`
	Loc            *time.Location `json:"-"`               // Initialized during load; seconds east of UTC
	SessionTimeout int            `json:"session_timeout"` // hours until the session is lost
	FormTimeout    int            `json:"form_timeout"`    // hours until a form post is rejected

	AppInstanceID int64    `json:"app_instance_id,omitempty"` // append to URLs of cached static jpg, js and css files - change to trigger reload
	LangCodes     []string `json:"lang_codes"`                // available language codes for the application, first element is default

	CPUProfile string `json:"cpu_profile"` // CPUProfile - output filename

	// Mp     - multi language strings for _all_      surveys   -  [key].Tr(lc)
	Mp trl.Map `json:"translations_generic"`
	// MpSite - multi language strings for _specific_ survey    -  [site][key].Tr(lc)
	// Contains 'default' key as fallback.
	// Use configT.Val() and qst.QuestionnaireT.SiteSpecificTrl() for comfort
	MpSite trl.MapSite `json:"translations_site"`

	// keep this last - since it trashes diff view
	CSSVars     cssVars            `json:"css_vars"`      // global CSS variables - no localization
	CSSVarsSite map[string]cssVars `json:"css_vars_site"` // [site|Survey.Type] specific CSS - overwrites/appends global css_vars - no localization

	AnonymousSurveyID string                       `json:"anonymous_survey_id,omitempty"` // on anonymous login - name of the survey into which the login is effected; also for redirect URL to LoginByHashID handler
	Profiles          map[string]map[string]string `json:"profiles"`                      // Profiles are sets of attributes, selected by the `p` parameter at login, containing key-values which are copied into the logged in user's attributes
	DirectLoginRanges []directLoginRangeT          `json:"direct_login_ranges,omitempty"` // DirectLoginRanges - user id to language preselection for direct login

}

ConfigT holds the application config

func Example

func Example() *ConfigT

Example writes a minimal configuration to file, to be extended or adapted

func Get

func Get() *ConfigT

Get provides access to the app configuration

func (c *ConfigT) AbsoluteLink() string

AbsoluteLink creates a HTTP URL

func (*ConfigT) Pref

func (c *ConfigT) Pref(pth ...string) string

Pref for templates: cfg.Pref

func (*ConfigT) Tr

func (c *ConfigT) Tr(langCode, key string) string

Tr for global translations in templates i.e. {{ cfg.Tr .Q.LangCode "correct_errors" }}

func (*ConfigT) Val

func (c *ConfigT) Val(site, langCode, key string) string

Val for site and language specific values in templates; function falls back to key "default"; i.e. {{ cfg.Val .Site "en" "app_label"}} or {{ cfg.Val .Site "default" "img_logo_icon"}} compare qst.QuestionaireT.SiteSpecificTrl

Jump to

Keyboard shortcuts

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