gserver

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: BSD-2-Clause Imports: 27 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gserver, in Go

gserver is an experimental web server adapted to serve OGDL templates along with static content. It is not optimized and not well tested, as of now.

Features

  • The file extension of (some) files below the document root is optional
  • Trailing slash and index files detection
  • Markdown rendering on the fly.
  • Login, Logout example functionality
  • Upload files go to /_user/file/$user/$folder/
  • Template functionality extensible through Go plugins

Parameter substitution in paths

While resolving a path in the document root, entries of the form _token are used for path elements not directly found in the file system. In that case 'token' will be available later as a variable, set to the unknown path element.

For example:

 /john/blog/1

will be sent to

/_user/blog/_id/index.htm

if that path is present. Two variables will be available in the context:

user=john
id=1

Routes

There are two routes configured in gserver:

/:user/file/*filepath
/*filepath

The first one goes to a static file handler that translates that path to /_user/file/:user/*filepath. This handler doesn't create or need sessions.

The second goes to a handler that uses the parameter substitution mechanism explained above, creates sessions, processes file uploads and templates.

Any path that has not the form /token/file/* goes to this second route.

The static handler will not return paths with elements that start with a dot. The dynamic handler, in addition, will ignore path with elements starting with an underscore, since these are reserved for variables.

File upload

Any POST request with files attached (multipart) and a field named "UploadFiles" that is handled by the second handler will store those files in /_user/file/$user/$folder/. $user is the current authenticated user and $folder is 'default' or the content of a field named 'folder' in the request.

Without an authenticated user no files will be stored in the server.

TODO: public and private files (ACL, casbin?)

Templates

TODO

Remote functions

OGDL remote functions (RPC endpoints) can be configured in .conf/config:

ogdlrf
  git
    host localhost:1135
  zoekt
    host localhost:1166

TODO: document in ogdl-go how to create servers and clients.

Plugins

Plugins that are present in .conf/plugin are loaded in made available in the request context. Public methods in those plugins can then be accessed in templates. If a plugin database.so is present, a Database object is expected which will be placed in the context so that $database.Method() can be called in the template.

Markdown processor ($MD())

TODO: describe the extensions and the \escape inline syntax for processing style and function calls.

Form to context

Form inputs are stored in the request's context and made directly accessible in templates. Input names are taken as simple paths (tokens separated by dots), and the special case where the name ends with ._ogdl is parsed as OGDL before stored in the context.

For example, the content of the following form:

<form>
<input name="obj.name" />
<input name="obj.conf._ogdl"/>

could be something like this:

obj
  name
    "Pepe Delgado"
  conf
    ip
      192.160.1.1
    net
      255.255.255.0

Login, Logout

There is no specific path for login or logout. Any request which does not go to the static file handler will recognize the parameters 'Login' and 'Logout' if present. The default login handler accepts any non-empty username and any password.

The 'redirect' parameter can be used to send the user to a specific page after login. The default behavior is to return to the same page.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TplExtensions []string = []string{".htm", ".txt", ".csv", ".json", ".g", ".ogdl", ".xml", ".xlsx", ".svg", ".ics"}

Functions

func AccessAdapter

func AccessAdapter(config string) func(http.Handler) http.Handler

func CreateUploadDir

func CreateUploadDir()

func DeleteRedirectCookie

func DeleteRedirectCookie(w http.ResponseWriter)

func DeleteUserCookie

func DeleteUserCookie(w http.ResponseWriter)

func FileHandler

func FileHandler() http.HandlerFunc

func GetACL

func GetACL(user string, srv *Server) string

func RedirectCookie

func RedirectCookie() *securecookie.Obj

RedirectCookie holds the post-login destination across the login form POST. It is a signed cookie rather than a session attribute because /login is reached anonymously, and stashing it server-side would let any unauthenticated client fill the session table.

func RedirectCookieValue

func RedirectCookieValue(r *http.Request) string

func SetRedirectCookie

func SetRedirectCookie(w http.ResponseWriter, path string)

func SetUserCookieKey

func SetUserCookieKey(key []byte)

SetUserCookieKey sets the session cookie HMAC key. key may be any length; it is hashed to the 32 bytes securecookie requires. An empty key is ignored, leaving the default in place. Call once at startup before serving.

func UserCookie

func UserCookie() *securecookie.Obj

func UserCookieValue

func UserCookieValue(r *http.Request) string

func WithUser

func WithUser(ctx context.Context, u *InjectedUser) context.Context

WithUser returns a copy of ctx carrying u, to be read by getSession().

Types

type InjectedUser

type InjectedUser struct {
	UID string
	ACL string
}

InjectedUser is an externally-resolved identity carried on the request context. UID maps to the "user" scalar; ACL, when non-empty, maps to the "userACL" scalar (a space-separated label set), bypassing the GetACL lookup.

type Request

type Request struct {
	HttpRequest *http.Request
	User        string
	Context     *ogdl.Graph
	Params      *ogdl.Graph
	Path        string
	File        *fn.FNode
	Mime        string
	// Session is nil for anonymous requests: a session is only stored once a
	// user authenticates.
	Session *session2.Session
}

func ConvertRequest

func ConvertRequest(r *http.Request, w http.ResponseWriter, host bool, srv *Server) *Request

func (*Request) Get

func (r *Request) Get() error

Get is a direct map from URL to file (binary content + params) TODO: Clean r.Path vs r.File.Path dicotomy

func (*Request) Process

func (r *Request) Process(srv *Server) error

Process processes templates, remaining path fragments and sets mime the type

type Server

type Server struct {
	Host           string
	SecureHost     string
	Hosts          []string
	Config         *ogdl.Graph
	HostContexts   map[string]*ogdl.Graph
	Context        *ogdl.Graph
	Root           *fn.FNode
	DocRoot        string
	UploadDir      string
	DefaultUser    string
	UserDb         *sql.DB
	MaxSessions    int
	SessionTimeout time.Duration
	Plugins        []string
	Login          login
	ContextService contextService
	DomainConfig   domainConfig
	Templates      map[string]*ogdl.Graph
	Multi          bool
	ContextMu      sync.RWMutex
	// contains filtered or unexported fields
}

func New

func New(host string) (*Server, error)

New prepares a Server{} structure initialized with configuration information and a base context that will be the initial context of each request.

func NewMulti

func NewMulti() (*Server, error)

New prepares a Server{} structure initialized with configuration information and a base context that will be the initial context of each request.

func NewWithConfig

func NewWithConfig(host string, config, context *ogdl.Graph) (*Server, error)

func (*Server) DynamicHandler

func (srv *Server) DynamicHandler(host bool) http.HandlerFunc

DynamicHandler ...

func (*Server) DynamicHandlerFn

func (srv *Server) DynamicHandlerFn(host bool, fs *fn.FNode) http.HandlerFunc

DynamicHandlerFn ...

func (*Server) InitSessions

func (srv *Server) InitSessions()

InitSessions installs the global session manager. It discards every stored session, so it must only be called at startup.

func (*Server) LoginAdapter

func (srv *Server) LoginAdapter(host bool, userdb string) func(http.Handler) http.Handler

LoginAdapter handles "Login" and "Logout"

Login: sets r.Form["user"] to the authenticated user name. Logout: removes the session Other: do nothing

func (*Server) Serve

func (srv *Server) Serve(secure bool, timeout int, router http.Handler, email string)

func (*Server) SetMaxSessions

func (srv *Server) SetMaxSessions(n int)

SetMaxSessions caps the number of concurrently stored sessions. Sessions are only stored for authenticated users, so this bounds concurrent logins; past the cap the least recently used session is evicted. 0 means unlimited.

func (*Server) Shutdown

func (srv *Server) Shutdown()

func (*Server) StaticFileHandler

func (srv *Server) StaticFileHandler(host, userspace, protect bool) http.HandlerFunc

StaticFileHandler returns a handler that processes static files.

if host is true, the hostname is prepended to the path if userspace is true, the first element of a path is taken as a user

func (*Server) StaticFileHandlerFn

func (srv *Server) StaticFileHandlerFn(host bool, fs *fn.FNode) http.HandlerFunc

StaticFileHandler returns a handler that processes static files.

if host is true, the hostname is prepended to the path

func (*Server) WatchContext

func (srv *Server) WatchContext(path string)

WatchContext watches the given context.ogdl file and reloads srv.Context whenever the file is written or replaced. Intended to be run as a goroutine.

type SessionContext

type SessionContext struct {
	Parent *ogdl.Graph // points to srv.Context or a host context; never written
	// contains filtered or unexported fields
}

SessionContext is a lightweight per-request overlay over the server's read-only context. Only session-specific values (user, userACL, R.*) are stored locally; everything else resolves from Parent without copying.

func (*SessionContext) Create

func (sc *SessionContext) Create(key string) *ogdl.Graph

func (*SessionContext) Get

func (sc *SessionContext) Get(key string) *ogdl.Graph

func (*SessionContext) Graph

func (sc *SessionContext) Graph() *ogdl.Graph

Graph builds a merged *ogdl.Graph for the template engine. Local nodes come first so they shadow parent entries of the same name. Parent entries are wrapped in shell nodes so writes during template processing cannot reach the shared srv.Context.

func (*SessionContext) Node

func (sc *SessionContext) Node(key string) *ogdl.Graph

func (*SessionContext) Set

func (sc *SessionContext) Set(key string, val interface{})

Directories

Path Synopsis
ctxreg
Package ctxreg is a dependency-free registry for template-context objects.
Package ctxreg is a dependency-free registry for template-context objects.
plugins/etoolsctx
Package etoolsctx registers electronics/etools under the "etools" context name.
Package etoolsctx registers electronics/etools under the "etools" context name.
plugins/filesctx
Package filesctx registers golib/files under the "files" context name.
Package filesctx registers golib/files under the "files" context name.
plugins/gosqlctx
Package gosqlctx registers golib/gosql under the "sql" context name.
Package gosqlctx registers golib/gosql under the "sql" context name.
plugins/htmlctx
Package htmlctx registers golib/html under the "html" context name.
Package htmlctx registers golib/html under the "html" context name.
plugins/isolationctx
Package isolationctx registers electronics/isolation under the "isolation" context name.
Package isolationctx registers electronics/isolation under the "isolation" context name.
plugins/stringsctx
Package stringsctx registers golib/strings under the "strings" context name.
Package stringsctx registers golib/strings under the "strings" context name.
Gserver is a web server.
Gserver is a web server.

Jump to

Keyboard shortcuts

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