gotuna

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2021 License: MIT Imports: 16 Imported by: 5

README

PkgGoDev rests status Go Report Card Go Report Card

GoTuna - Web framework for Go

GoTuna a lightweight web framework for Go with mux router, middlewares, user sessions, templates, embedded views, and static file server.

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

Quick Start

Initialize new app and install GoTuna:

mkdir testapp
cd testapp
go get -u github.com/gotuna/gotuna

Now create two files main.go and app.html as an example:

// main.go

package main

import (
	"fmt"
	"net/http"
	"os"

	"github.com/gotuna/gotuna"
)

func main() {
	app := gotuna.App{
		ViewFiles: os.DirFS("."),
		Router:    gotuna.NewMuxRouter(),
	}
	
	app.Router.Handle("/", handlerHome(app))
	app.Router.Handle("/login", handlerLogin(app)).Methods(http.MethodGet, http.MethodPost)

	fmt.Println("Running on http://localhost:8888")
	http.ListenAndServe(":8888", app.Router)
}

func handlerHome(app gotuna.App) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		app.NewTemplatingEngine().
			Render(w, r, "app.html")
	})
}

func handlerLogin(app gotuna.App) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Login form...")
	})
}

This will be your app's html layout:

// app.html

{{- define "app" -}}
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <a href="/login">Please login!</a>
  </body>
</html>
{{- end -}}

Run this simple app and visit http://localhost:8888 in your browser:

go run main.go

Running example apps

GoTuna comes with an example app. Make sure you have git and Go >= 1.16 installed.

git clone https://github.com/gotuna/gotuna.git
cd gotuna
go run examples/fullapp/cmd/main.go

Testing

go test -race -v ./...

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")
	// ErrNotUnique is thrown when we try to add new user with existing ID
	ErrNotUnique = constError("user with this ID already exists")
)
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 OPTIONS request and respond with 204 status.

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) StoreParamsToContext added in v0.5.0

func (app App) StoreParamsToContext() MiddlewareFunc

StoreParamsToContext middleware will add all parameters from the current request to the context, this includes query, form, and route params

func (App) StoreUserToContext

func (app App) StoreUserToContext() MiddlewareFunc

StoreUserToContext middleware will add the current logged in user object (if any) to the request context for further use.

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 InMemoryUserRepository added in v0.4.1

type InMemoryUserRepository struct {
	Users []InMemoryUser
}

InMemoryUserRepository is a sample in-memory UserRepository

func (*InMemoryUserRepository) AddUser added in v0.4.1

func (u *InMemoryUserRepository) AddUser(user InMemoryUser) error

AddUser will add user to the repository or return error if ID is not unique or blank

func (InMemoryUserRepository) Authenticate added in v0.4.1

func (u InMemoryUserRepository) Authenticate(w http.ResponseWriter, r *http.Request) (User, error)

Authenticate tries to authenticate the user when submitting the login form

func (InMemoryUserRepository) GetUserByID added in v0.4.1

func (u InMemoryUserRepository) GetUserByID(id string) (User, error)

GetUserByID will try to find and return the user with this ID from the repository

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) GetLocale added in v0.5.0

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

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

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) 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) SetLocale added in v0.5.0

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

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

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.

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
test

Jump to

Keyboard shortcuts

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