gotuna

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2021 License: MIT Imports: 16 Imported by: 8

README

PkgGoDev Tests Status Go Report Card Go Report Card

GoTuna - Web framework for Go

Please visit https://gotuna.org for the latest documentation, examples, and more.

Features

  • Router (gorilla)
  • Standard http.Handler interface
  • Middleware support
  • User session management (gorilla)
  • Session flash messages
  • Native view rendering (html/template) with helpers
  • Static file server included with the configurable prefix
  • Standard logger interface
  • Request logging and panic recovery
  • Full support for embedded templates and static files
  • User authentication (via user provider interface)
  • Sample InMemory user provider included
  • Multi-language support
  • Database agnostic

Requirements

  • Make sure you have Go >= 1.16 installed

Testing

go test -race -v ./...

Running examples

go run examples/fullapp/cmd/main.go

External dependencies

External modules are mostly used when the feature is too complex to build or maintain - Router, Secure cookies

TODO

  • Validation (input/forms)
  • Cache

Licence

This project is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	// UserIDKey is used as session key to store the current's user unique ID.
	UserIDKey = "_user_id"
	// UserLocaleKey is used as session key for the current's user locale settings.
	UserLocaleKey = "_user_locale"
)
View Source
const ContentTypeHTML = "text/html; charset=utf-8"

ContentTypeHTML is a standard Content-Type header for HTML response.

Variables

View Source
var (
	// ErrCannotGetSession is thrown when we cannot retrieve a valid session from the store
	ErrCannotGetSession = constError("cannot get session from the store")
	// ErrNoValueForThisKey is thrown when we cannot get a value for provided key
	ErrNoValueForThisKey = constError("session holds no value for this key")
)
View Source
var (
	// ErrWrongPassword is thrown on bad password
	ErrWrongPassword = constError("wrong password")
	// ErrCannotFindUser is thrown when we cannot match user
	ErrCannotFindUser = constError("user not found")
	// ErrRequiredField is thrown when requestfield is required
	ErrRequiredField = constError("this field is required")
)
View Source
var ErrNoUserInContext = constError("no user in the context")

ErrNoUserInContext is thrown when we cannot extract the User from the current context

Functions

func ContextWithParams added in v0.3.0

func ContextWithParams(ctx context.Context, vars url.Values) context.Context

ContextWithParams returns a context with all the input parameters for the current request query/form/route

func ContextWithUser

func ContextWithUser(ctx context.Context, user User) context.Context

ContextWithUser returns a context with a User value inside

func GetParam added in v0.3.0

func GetParam(ctx context.Context, param string) string

GetParam return specific request parameter (query/form/route)

func NewMuxRouter added in v0.3.0

func NewMuxRouter() *mux.Router

NewMuxRouter returns the underlying mux router instance

func TypeFromString

func TypeFromString(raw string, t interface{}) error

TypeFromString converts JSON-encoded value into the type t.

func TypeToString

func TypeToString(t interface{}) (string, error)

TypeToString converts any type t to JSON-encoded string value. This is used because app's session can only hold basic string values.

Types

type App

type App struct {
	Logger         *log.Logger
	Router         *mux.Router
	Static         fs.FS
	StaticPrefix   string
	ViewFiles      fs.FS
	ViewHelpers    []ViewHelperFunc
	Session        *Session
	SessionName    string
	UserRepository UserRepository
	Locale         Locale
}

App is the main app dependency store. This is where all the app's dependencies are configured.

func (App) Authenticate

func (app App) Authenticate(destination string) MiddlewareFunc

Authenticate middleware will redirect all guests to the destination. This is used to guard user-only routes and to force guests to login.

func (App) Cors

func (app App) Cors() MiddlewareFunc

Cors middleware will add CORS headers to every request.

func (App) Logging

func (app App) Logging() MiddlewareFunc

Logging middleware is used to log every requests to the app's Logger.

func (App) NewTemplatingEngine

func (app App) NewTemplatingEngine() TemplatingEngine

NewTemplatingEngine is a constructor that returns a native HTML templating engine.

func (App) Recoverer

func (app App) Recoverer(destination string) MiddlewareFunc

Recoverer middleware is used to recover the app from panics, to log the incident, and to redirect user to the error page.

func (App) RedirectIfAuthenticated

func (app App) RedirectIfAuthenticated(destination string) MiddlewareFunc

RedirectIfAuthenticated middleware will redirect authenticated users to the destination. This is used to deflect logged in users from guest-only pages like login or register page back to the app.

func (App) ServeFiles

func (app App) ServeFiles(notFound http.Handler) http.Handler

ServeFiles returns a Handler that serves a HTTP requests with the file contents.

You can pass 404 Handler to be served when the file is not found.

It will not list directories, instead, the 404 Handler will be used.

func (App) StoreToContext added in v0.3.0

func (app App) StoreToContext() MiddlewareFunc

StoreToContext middleware will add common values to the context for further use this includes all of the parameters for the current request query/form/route and the current logged in user (if any)

type FlashMessage

type FlashMessage struct {
	Message   string
	Kind      string
	AutoClose bool
}

FlashMessage represents a flash message.

func NewFlash

func NewFlash(message string) FlashMessage

NewFlash is a constructor for new flash message.

type InMemoryUser

type InMemoryUser struct {
	ID       string
	Email    string
	Name     string
	Password string
}

InMemoryUser is a sample User entity implementation with some sample fields provided like Name and Email.

Password is stored as plain-text for simplicity. In real life, you should probably use crypto/bcrypt library and store hashed representation and compare passwords in Authenticate method with bcrypt.CompareHashAndPassword

func (InMemoryUser) GetID

func (u InMemoryUser) GetID() string

GetID will return a unique ID for every specific user.

type Locale

type Locale interface {
	T(language string, s string, p ...interface{}) string
	TP(language string, s string, n int, p ...interface{}) string
}

Locale is the main i18n interface.

func NewLocale

func NewLocale(set map[string]map[string]string) Locale

NewLocale creates a new i18n instance.

type MiddlewareFunc added in v0.3.1

type MiddlewareFunc = mux.MiddlewareFunc

MiddlewareFunc is mux.MiddlewareFunc alias

type Session

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

Session is the main application session store.

func NewSession

func NewSession(store sessions.Store, name string) *Session

NewSession returns a new application session with requested store engine.

func (Session) Delete

func (s Session) Delete(w http.ResponseWriter, r *http.Request, key string) error

Delete value from the session for key.

func (Session) Destroy

func (s Session) Destroy(w http.ResponseWriter, r *http.Request) error

Destroy the user session by removing the user key and expiring the cookie.

func (Session) Flash

func (s Session) Flash(w http.ResponseWriter, r *http.Request, flashMessage FlashMessage) error

Flash will store flash message into the session. These messages are primarily used to inform the user during a subsequesnt request about some status update.

func (Session) Flashes

func (s Session) Flashes(w http.ResponseWriter, r *http.Request) []FlashMessage

Flashes returns all messages from the session and removes them.

func (Session) Get

func (s Session) Get(r *http.Request, key string) (string, error)

Get string value from the session for specified key.

func (Session) GetUserID

func (s Session) GetUserID(r *http.Request) (string, error)

GetUserID retrieves the current user's unique ID from the session.

func (Session) GetUserLocale

func (s Session) GetUserLocale(r *http.Request) string

GetUserLocale retrieves the current user's locale string from the session.

func (Session) IsGuest

func (s Session) IsGuest(r *http.Request) bool

IsGuest checks if current user is not logged in into the app.

func (Session) Put

func (s Session) Put(w http.ResponseWriter, r *http.Request, key string, value string) error

Put string value in the session for specified key.

func (Session) SetUserID

func (s Session) SetUserID(w http.ResponseWriter, r *http.Request, id string) error

SetUserID will save the current user's unique ID into the session.

func (Session) SetUserLocale

func (s Session) SetUserLocale(w http.ResponseWriter, r *http.Request, id string) error

SetUserLocale will store the user's locale string into the session.

type TemplatingEngine

type TemplatingEngine interface {
	Render(w http.ResponseWriter, r *http.Request, patterns ...string)
	Set(key string, data interface{}) TemplatingEngine
	SetError(errorKey, description string) TemplatingEngine
	GetErrors() map[string]string
}

TemplatingEngine used for rendering response.

type User

type User interface {
	GetID() string
}

The User interface for providing the standard user entity.

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (User, error)

GetUserFromContext extracts and returns the User from the context

type UserRepository

type UserRepository interface {
	GetUserByID(id string) (User, error)
	Authenticate(w http.ResponseWriter, r *http.Request) (User, error)
}

The UserRepository will provide a way to retrieve and authenticate users.

The user repository is database-agnostic. You can keep your users in MySQL, MongoDB, LDAP or in a simple JSON file. By implementing this interface, you are providing the way for the app to authenticate, and retrieve the specific user entity by using the unique user ID.

func NewInMemoryUserRepository

func NewInMemoryUserRepository(users []InMemoryUser) UserRepository

NewInMemoryUserRepository returns a sample in-memory UserRepository implementation which can be used in tests or sample apps.

type ViewHelperFunc

type ViewHelperFunc func(w http.ResponseWriter, r *http.Request) (string, interface{})

ViewHelperFunc is a view helper that can be used in any template file.

Directories

Path Synopsis
examples
basic/cmd command
fullapp/cmd command
test

Jump to

Keyboard shortcuts

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