webapp

package
v0.0.0-...-f040671 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2022 License: BSD-3-Clause Imports: 18 Imported by: 0

README

webapp

webapp is a lightweight, yet fully featured full stack web framework

webapp contains the following "modules" available through the WebApp:

  • templates which provides a template engine and handles caching
  • sessions which handles authentication and session management
  • logger which handles leveled http logging and metrics
  • servemux which provides a http request multiplexer
  • middleware which provides http middleware options and helpers
  • httperror which provides some default http error handling options

Everything in the webapp package was designed to fit together nicely, while still remaining small and easy to use.

We tried to keep as many things standard library compatible as we could. Anything that is not standard library compatible will be listed below:

  • NA

Documentation

Index

Constants

View Source
const (
	LevelDebug logLevel = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
	LevelOff
)

Variables

View Source
var HTTPCodesLongFormat = map[int]string{
	100: "Continue. This means that the server in question has received your browser’s request headers, and is now ready for the request body to be sent as well. This makes the request process more efficient since it prevents the browser from sending a body request even though the headers have been rejected.",
	101: "Switching protocols. Your browser has asked the server to change protocols, and the server has complied.",
	103: "Early hints. This returns some response headers before the rest of the server’s response is ready.",

	200: "Everything is OK. This is the code that is delivered when a web page or resource acts exactly the way it’s expected to.",
	201: "Created. The server has fulfilled the browser’s request, and as a result, has created a new resource.",
	202: "Accepted. The server has accepted your browser’s request but is still processing it. The request ultimately may or may not result in a completed response.",
	203: "Non-Authoritative Information. This status code may appear when a proxy is in use. It means that the proxy server received a 200 Everything is OK status code from the origin server, but has modified the response before passing it on to your browser.",
	204: "No Content. This code means that the server has successfully processed the request, but is not going to return any content.",
	205: "Reset Content. Like a 204 code, this means that how server has processed the request but is not going to return any content. However, it also requires that your browser resets the document view.",
	206: "Partial Content. You may see this status code if your HTTP client (also known as your browser) uses ‘range headers’. This enables your browser to resume paused downloads, as well as to split a download into multiple streams. A 206 code is sent when a range header causes the server to send only part of the requested resource.",

	300: "Multiple Choices. Sometimes, there may be multiple possible resources the server can respond with to fulfill your browser’s request. A 300 status code means that your browser now needs to choose between them. This may occur when there are multiple file type extensions available, or if the server is experiencing word sense disambiguation.",
	301: "The requested resource has been moved permanently. This code is delivered when a web page or resource has been permanently replaced with a different resource. It is used for permanent URL redirection.",
	302: "The requested resource has moved, but was found. This code is used to indicate that the requested resource was found, just not at the location where it was expected. It is used for temporary URL redirection.",
	303: "See Other. Understanding a 303 status code requires that you know the difference between the four primary HTTP request methods. Essentially, a 303 code tells your browser that it found the resource your browser requested via POST, PUT, or DELETE. However, to retrieve it using GET, you need to make the appropriate request to a different URL than the one you previously used.",
	304: "The requested resource has not been modified since the last time you accessed it. This code tells the browser that the resources stored in the browser cache haven’t changed. It’s used to speed up web page delivery by reusing previously-downloaded resources.",
	307: "Temporary Redirect. This status code has replaced 302 “Found” as the appropriate action when a resource has been temporarily moved to a different URL. Unlike the 302 status code, it does not allow the HTTP method to change.",
	308: "Permanent Redirect. The 308 status code is the successor to the 301 “Moved Permanently” code. It does not allow the HTTP method to change and indicates that the requested resource is now permanently located at a new URL.",

	400: "Bad Request. The server can’t return a response due to an error on the client’s end. See our guide for resolving this error.",
	401: "Unauthorized or Authorization Required. This is returned by the server when the target resource lacks valid authentication credentials. You might see this if you’ve set up basic HTTP authentication using htpasswd.",
	402: "Payment Required. Originally, this code was created for use as part of a digital cash system. However, that plan never followed through. Instead, it’s used by a variety of platforms to indicate that a request cannot be fulfilled, usually due to a lack of required funds.",
	403: "Access to that resource is forbidden. This code is returned when a user attempts to access something that they don’t have permission to view. For example, trying to reach password-protected content without logging in might produce a 403 error.",
	404: "The requested resource was not found. This is the most common error message of them all. This code means that the requested resource does not exist, and the server does not know if it ever existed.",
	405: "Method not allowed. This is generated when the hosting server (origin server) supports the method received, but the target resource doesn’t.",
	406: "Not acceptable response. The requested resource is capable of generating only content that is not acceptable according to the accept headers sent in the request.",
	407: "Proxy Authentication Required. A proxy server is in use and requires your browser to authenticate itself before continuing.",
	408: "The server timed out waiting for the rest of the request from the browser. This code is generated when a server times out while waiting for the complete request from the browser. In other words, the server didn’t get the full request that was sent by the browser. One possible cause could be net congestion resulting in the loss of data packets between the browser and the server.",
	409: "Conflict. A 409 status code means that the server couldn’t process your browser’s request because there’s a conflict with the relevant resource. This sometimes occurs due to multiple simultaneous edits.",
	410: "The requested resource is gone and won’t be coming back. This is similar to a 404 “Not Found” code, except a 410 indicates that the condition is expected and permanent.",
	411: "Length Required. This means that the requested resource requires that the client specify a certain length and that it did not.",
	412: "Precondition Failed. Your browser included certain conditions in its request headers, and the server did not meet those specifications.",
	413: "Payload Too Large or “Request Entity Too Large.” Your request is larger than the server is willing or able to process.",
	414: "URI Too Long. This is usually the result of a GET request that has been encoded as a query string that is too large for the server to process.",
	415: "Unsupported Media Type. The request includes a media type that the server or resource doesn’t support.",
	416: "Range Not Satisfiable. Your request was for a portion of a resource that the server is unable to return.",
	417: "Expectation Failed. The server is unable to meet the requirements specified in the request’s expect header field.",
	418: "I’m a teapot. This code is returned by teapots that receive requests to brew coffee. It’s also an April Fool’s Joke from 1998.",
	422: "Unprocessable Entity. The client request contains semantic errors, and the server can’t process it.",
	425: "Too Early. This code is sent when the server is unwilling to process a request because it may be replayed.",
	426: "Upgrade Required. Due to the contents of the request’s upgrade header field, the client should switch to a different protocol.",
	428: "Precondition Required. The server requires conditions to be specified before processing the request.",
	429: "Too many requests. This is generated by the server when the user has sent too many requests in a given amount of time (seconds-limiting). This can sometimes occur due to bots or scripts attempting to access your site. In this case, you might want to try changing your WordPress login URL. You can also check out our guide to fixing a 429 “Too Many Requests” error.",
	431: "Request Header Fields Too Large. The server can’t process the request because the header fields are too large. This may indicate a problem with a single header field, or all of them collectively.",
	451: "Unavailable for Legal Reasons. The operator of the server has received a demand to prohibit access to the resource you’ve requested (or a set of resources including the one you’ve requested). Fun fact: This code is a reference to Ray Bradbury’s novel Fahrenheit 451.",
	499: "Client closed request. This is returned by NGINX when the client closes the request while Nginx is still processing it.",

	500: "There was an error on the server and the request could not be completed. This is generic code that simply means “internal server error”. Something went wrong on the server and the requested resource was not delivered. This code is typically generated by third-party plugins, faulty PHP, or even the connection to the database breaking. Check out our tutorials on how to fix the error establishing a database connection and other ways to resolve a 500 internal server error.",
	501: "Not Implemented. This error indicates that the server does not support the functionality required to fulfill the request. This is almost always a problem on the web server itself, and usually must be resolved by the host. Check out our recommendations on how to resolve a 501 not implemented error.",
	502: "Bad Gateway. This error code typically means that one server has received an invalid response from another, such as when a proxy server is in use. Other times a query or request will take too long, and so it is canceled or killed by the server and the connection to the database breaks. For more details, see our in-depth tutorial on how to fix the 502 Bad Gateway error.",
	503: "The server is unavailable to handle this request right now. The request cannot be completed at this point in time. This code may be returned by an overloaded server that is unable to handle additional requests. We have a full guide on how to fix the 503 Service Unavailable Error.",
	504: "The server, acting as a gateway, timed out waiting for another server to respond. This is the code returned when there are two servers involved in processing a request, and the first server times out waiting for the second server to respond. You can read more about how to fix 504 errors in our dedicated guide.",
	505: "HTTP Version Not Supported. The server doesn’t support the HTTP version the client used to make the request.",
	508: "Resource Limit Is Reached limits on resources set by your web host have been reached. Check out our tutorial on how to resolve “508 Resource Limit Is Reached” error.",
	511: "Network Authentication Required. This status code is sent when the network you’re trying to use requires some form of authentication before sending your request to the server. For instance, you may need to agree to the Terms and Conditions of a public Wi-Fi hotspot.",
	521: "Web server is down. Error 521 is a Cloudflare-specific error message. It means that your web browser was able to successfully connect to Cloudflare, but Cloudflare was not able to connect to the origin web server.",
	525: "SSL Handshake Failed. Error 525 means that the SSL handshake between a domain using Cloudflare and the origin web server failed. If you are experiencing issues there are five methods you can try to easily fix error 525.",
}

Functions

func AddTime

func AddTime(t time.Time, duration time.Duration) time.Time

func AuthHandler

func AuthHandler(dao DataAccesser) http.Handler

func Base64Decode

func Base64Decode(s string) string

Base64Decode takes a base64 encoded string and returns a plaintext string

func Base64Encode

func Base64Encode(s string) string

Base64Encode takes a plaintext string and returns a base64 encoded string

func DefaultMuxerErrorHandler

func DefaultMuxerErrorHandler() http.Handler

func DefaultMuxerStaticHandler

func DefaultMuxerStaticHandler(path string) http.Handler

func FileHasChanged

func FileHasChanged(file string, lastModTime int64) (int64, bool)

func HandleSignalInterrupt

func HandleSignalInterrupt(msg string, args ...interface{})

func HandleSignalInterruptFunc

func HandleSignalInterruptFunc(fn func(), msg string, args ...interface{})

func LevelText

func LevelText(level logLevel) string

func RandStringN

func RandStringN(n int) string

RandStringN creates a random string N characters in length

func StaticHandler

func StaticHandler(prefix, path string) http.Handler

func URLDecode

func URLDecode(s string) string

URLDecode takes a URL encoded string and returns a plaintext string

func URLEncode

func URLEncode(s string) string

URLEncode takes a plaintext string and returns a URL encoded string

Types

type Application

type Application struct {
	// contains filtered or unexported fields
}

func NewApplication

func NewApplication(conf *ApplicationConfig) *Application

func (*Application) ListenAndServe

func (app *Application) ListenAndServe() error

func (*Application) SessionStore

func (app *Application) SessionStore() *SessionStore

func (*Application) SetServerHandler

func (app *Application) SetServerHandler(h http.Handler)

func (*Application) TemplateCache

func (app *Application) TemplateCache() *TemplateCache

func (*Application) WebServer

func (app *Application) WebServer() *WebServer

type AuthUser

type AuthUser interface {
	Register(username, password, role string)
	Authenticate(username, password string) (*SystemUser, bool)
}

type AutoID

type AutoID struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*AutoID) ID

func (a *AutoID) ID() (id int)

type Chain

type Chain struct {
	// contains filtered or unexported fields
}

Chain acts as a list of http.Handler middlewares. It's effectively immutable.

func NewChain

func NewChain(mw ...Middleware) *Chain

NewChain creates a new chain, memorizing the given list of middleware handlers. New serves no other function, middlewares are only called upon a call to Then().

func (*Chain) Append

func (c *Chain) Append(mw ...Middleware) *Chain

Append extends a chain, adding the specified constructors as the last ones in the request flow.

func (*Chain) Extend

func (c *Chain) Extend(chain *Chain) *Chain

Extend extends a chain by adding the specified chain as the last one in the request flow.

func (*Chain) Then

func (c *Chain) Then(handler http.Handler) http.Handler

Then chains the middleware and returns the final http.Handler. Then() treats nil as http.DefaultServeMux.

func (*Chain) ThenFunc

func (c *Chain) ThenFunc(handler http.HandlerFunc) http.Handler

ThenFunc works identically to Then, but takes a HandlerFunc instead of a Handler.

type Controller

type Controller interface {
	AddService(service Servicer)
	HandleBase() http.Handler
}

type DataAccesser

type DataAccesser interface {
	Add(e Entity) (int, error)  // add a new entity, return id or error
	Get(id int) (Entity, error) // get an entity by id, return any error
	GetAll() ([]Entity, error)  // get all entities, return number found or error
	Set(e Entity) error         // update an existing entity by id, return any error
	Del(id int) error           // delete an existing entity by id
}

type Entity

type Entity interface {
	GetID() int
	SetID(id int)
}

type Logger

type Logger struct {
	*log.Logger
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(level logLevel) *Logger

func (*Logger) Debug

func (l *Logger) Debug(s string, a ...interface{})

func (*Logger) Error

func (l *Logger) Error(s string, a ...interface{})

func (*Logger) Fatal

func (l *Logger) Fatal(s string, a ...interface{})

func (*Logger) Info

func (l *Logger) Info(s string, a ...interface{})

func (*Logger) Warn

func (l *Logger) Warn(s string, a ...interface{})

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware is a piece of middleware.

type Muxer

type Muxer struct {
	// contains filtered or unexported fields
}

func NewMuxer

func NewMuxer(conf *MuxerConfig) *Muxer

func (*Muxer) ContentType

func (s *Muxer) ContentType(w http.ResponseWriter, content string)

func (*Muxer) Delete

func (s *Muxer) Delete(pattern string, handler http.Handler)

func (*Muxer) Forward

func (s *Muxer) Forward(oldpattern string, newpattern string)

func (*Muxer) Get

func (s *Muxer) Get(pattern string, handler http.Handler)

func (*Muxer) GetEntries

func (s *Muxer) GetEntries() []string

func (*Muxer) Handle

func (s *Muxer) Handle(method string, pattern string, handler http.Handler)

func (*Muxer) HandleFunc

func (s *Muxer) HandleFunc(method, pattern string, handler func(http.ResponseWriter, *http.Request))

func (*Muxer) Len

func (s *Muxer) Len() int

func (*Muxer) Less

func (s *Muxer) Less(i, j int) bool

func (*Muxer) Post

func (s *Muxer) Post(pattern string, handler http.Handler)

func (*Muxer) Put

func (s *Muxer) Put(pattern string, handler http.Handler)

func (*Muxer) Search

func (s *Muxer) Search(x string) int

func (*Muxer) ServeHTTP

func (s *Muxer) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Muxer) Static

func (s *Muxer) Static(pattern string, path string)

func (*Muxer) Swap

func (s *Muxer) Swap(i, j int)

type MuxerConfig

type MuxerConfig struct {
	StaticHandler http.Handler
	ErrHandler    http.Handler
	MetricsOn     bool
	Logging       int
}

type Path

type Path struct {
	Path string
	ID   string
}

func NewPath

func NewPath(p string) *Path

func (*Path) HasID

func (p *Path) HasID() bool

type Repository

type Repository interface {
	AddDataAccesser(dao DataAccesser)
}

type Server

type Server struct {
	*ServerConfig
	*http.Server
}

func NewServer

func NewServer(conf *ServerConfig) *Server

type ServerConfig

type ServerConfig struct {
}

type Servicer

type Servicer interface {
	AddRepository(repository Repository)
}

type Session

type Session struct {
	// contains filtered or unexported fields
}

func (*Session) Del

func (s *Session) Del(k string)

func (*Session) ExpiresIn

func (s *Session) ExpiresIn() int64

func (*Session) Get

func (s *Session) Get(k string) (interface{}, bool)

func (*Session) Has

func (s *Session) Has(k string) bool

func (*Session) ID

func (s *Session) ID() string

func (*Session) Set

func (s *Session) Set(k string, val interface{})

type SessionConfig

type SessionConfig struct {
	SessionID string        // SessionID is the global session id
	Domain    string        // Domain is the domain to limit the session scope
	Timeout   time.Duration // Timeout is the max idle session time allowed
}

SessionConfig is a configuration object for a session manager

type SessionManager

type SessionManager interface {
	// New should create and return a new session
	New() *Session

	// Get should return a cached session
	Get(r *http.Request) (*Session, bool)

	// Save should persist session to the underlying store
	// implementation. Passing a nil session erases it.
	Save(w http.ResponseWriter, r *http.Request, s *Session)
}

type SessionStore

type SessionStore struct {
	*SessionConfig
	// contains filtered or unexported fields
}

SessionStore implements the session manager interface and is a basic session manager using cookies.

func NewSessionStore

func NewSessionStore(conf *SessionConfig) *SessionStore

NewSessionStore takes a session id and a make session timeout. The sid will be used as the key for all session cookies, and the timeout is the maximum allowable idle session time before the session is expired

func (*SessionStore) Get

func (ss *SessionStore) Get(r *http.Request) (*Session, bool)

Get returns a cached session (if one exists)

func (*SessionStore) New

func (ss *SessionStore) New() *Session

New creates and returns a new session

func (*SessionStore) Save

func (ss *SessionStore) Save(w http.ResponseWriter, r *http.Request, session *Session)

Save persists the provided session. If you would like to remove a session, simply pass it a nil session, and it will time the cookie out.

func (*SessionStore) String

func (ss *SessionStore) String() string

String is the session store's stringer method

type SystemSessionUser

type SystemSessionUser struct {
	// contains filtered or unexported fields
}

func NewSystemSessionUser

func NewSystemSessionUser() *SystemSessionUser

func (*SystemSessionUser) Authenticate

func (a *SystemSessionUser) Authenticate(username, password string) (*SystemUser, bool)

func (*SystemSessionUser) Register

func (a *SystemSessionUser) Register(username, password, role string)

type SystemUser

type SystemUser struct {
	Username string
	Password string
	Role     string
}

type TemplateCache

type TemplateCache struct {
	*TemplateConfig
	// contains filtered or unexported fields
}

func NewTemplateCache

func NewTemplateCache(conf *TemplateConfig) *TemplateCache

func (*TemplateCache) DefinedTemplates

func (tc *TemplateCache) DefinedTemplates() string

func (*TemplateCache) ExecuteTemplate

func (tc *TemplateCache) ExecuteTemplate(w http.ResponseWriter, name string, data interface{})

func (*TemplateCache) Lookup

func (tc *TemplateCache) Lookup(name string) *template.Template

func (*TemplateCache) ParseGlob

func (tc *TemplateCache) ParseGlob(pattern string)

func (*TemplateCache) ReloadTemplates

func (tc *TemplateCache) ReloadTemplates()

type TemplateConfig

type TemplateConfig struct {
	BasePattern   string
	ExtraPatterns []string
	FuncMap       template.FuncMap
}

type WebApp

type WebApp struct {
	AuthUser
	*WebAppConfig
	*TemplateCache
	*SessionStore
	*Muxer
	*Server
	// contains filtered or unexported fields
}

func NewWebApp

func NewWebApp(conf *WebAppConfig) *WebApp

func (*WebApp) HandleLogin

func (app *WebApp) HandleLogin() http.Handler

func (*WebApp) HandleRegister

func (app *WebApp) HandleRegister() http.Handler

func (*WebApp) Redirect

func (app *WebApp) Redirect(url string) http.Handler

type WebAppConfig

type WebAppConfig struct {
	Templates          *TemplateConfig
	Sessions           *SessionConfig
	Muxer              *MuxerConfig
	Server             *ServerConfig
	AppName            string
	GracefulShutdownOn bool
}

type WebServer

type WebServer struct {
	// contains filtered or unexported fields
}

func NewWebServer

func NewWebServer(conf *WebServerConfig) *WebServer

type WebServerConfig

type WebServerConfig struct {
	ListenAddr     string
	DefaultHandler http.Handler
}

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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