rufus

package module
v0.0.0-...-60cc1aa Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2018 License: MIT Imports: 29 Imported by: 0

README

Rufus, Web-Framework

Disclaimer

I've built Rufus for personal usage but decided to open-source it, in case someone else finds it useful. Feedback and other proposals are welcomed.

Example project

Features

  • uses Chi as router
  • can render json, normal SSR websites and SSR templates for isomorphic websites
  • handles translation
  • automatic SSL via LetsEncrypt for production
  • self-signed certs for development
  • custom middleware:
    • in-memory response cache (you can plugin your own as well)
    • logger ( zerolog )
    • redirect www to no-www
    • content-type setting for json, SSR or "stripped" SSR

To-Do

  • probably more testing
  • A/B Testing middleware

Install

go get -u github.com/abenz1267/rufus

Usage

Code examples are taken from the example project

Preperation

To start using Rufus you need a few basic files:

  • config.json
  • translation.json, if you want to use the translation feature

You can find examples in this project or the example project linked at the top.

Loading up Rufus
app := &rufus.App{}

if err := app.LoadConfigAndRouter(); err != nil {
	log.Fatal(err)
}
Using shipped in-memory response cache
cache := &rufus.Cache{}
app.Middleware.Cache = cache

To invalidate the cache for a given URL

deleted := app.Cache.Invalidate(URL)
Registering routes
// main.go

go registerRoutes(app)
// routes.go

func registerRoutes(app *rufus.App) {
    for i := 0; i < app.Translation.Amount; i++ {
	language := <-app.RoutesSender

	if language == "default" {
	language = app.Language
	}

	r := chi.NewRouter()
	app.Router.PrependMiddleware(r, app.Server, app.CSPPolicy)

	r.NotFound(handlers.NotFound{App: app, Language:language.Get)

        handlers.Index{App: app, Language: language}.GetRoutes(r)
        handlers.About{App: app, Language: language}.GetRoutes(r)

	app.RoutesReceiver <- r
    }
}
Example handler
// handlers/about.go

type About struct {
	App         *rufus.App `json:"-"`
	Language    string     `json:"language,omitempty"`
	Title       string     `json:"title,omitempty"`
	Description string     `json:"description,omitempty"`
}

// GetRoutes registers routes for About handler
func (h About) GetRoutes(r *chi.Mux) {
	var url strings.Builder
	url.WriteString("/")

	if h.App.Translation.Amount > 1 {
		url.WriteString(h.App.TranslateURL("about", h.Language))
	} else {
		url.WriteString("about")
	}

	r.Get(url.String(), h.get)
}

func (h About) get(w http.ResponseWriter, r *http.Request) {
	h.Title = "About Page"
	h.Description = "This is a description"

    resp := rufus.Response{Status: http.StatusOK, TemplateFile: "about", Data: h}

	h.App.Response = resp

	h.App.Render(w, r)
}

Translation

Rufus does a few things:

  • handles translated routes
  • creates URLs based on the language
  • comes with two simple translation functions that can be used in templates as well as in functions
    • translate
      • template: {{ translate "phrase" "de" }}
      • function: App.Translation.Translate("phrase", "de")
    • translateURL

When a translation file is present it will also change the way routes are registered automatically, f.e.

without translation file: https://myapp.com/home

with translation file: https://myapp.com/de/startseite or https://myapp.com/en/home

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	Server      server `json:"server,omitempty"`
	Router      `json:"router,omitempty"`
	Translation `json:"-"`
	Templates   `json:"templates,omitempty"`
	Response    `json:"-"`
	Language    string `json:"language,omitempty"`
	CSPPolicy   string `json:"csp_policy,omitempty"`
}

App is the main Rufus instance

func (*App) LoadConfigAndRouter

func (a *App) LoadConfigAndRouter() error

LoadConfigAndRouter loads data from 'config.json' and sets chi router

func (*App) Render

func (a *App) Render(w http.ResponseWriter, r *http.Request)

Render handles and generates the response

func (*App) Start

func (a *App) Start() error

Start checks the environment set (development or production) and starts an according server

type Cache

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

Cache is a response cache middleware

func (*Cache) Check

func (c *Cache) Check() func(next http.Handler) http.Handler

Check is used to perform the caching

func (*Cache) Invalidate

func (c *Cache) Invalidate(path string) bool

Invalidate is used to delete a cache entry

type Middleware

type Middleware struct {
	RedirectToNonWWW    bool `json:"redirect_to_non_www,omitempty"`
	EnableResponseCache bool `json:"enable_response_cache,omitempty"`
	Cache               responseCache
}

Middleware struct for rufus

type Response

type Response struct {
	Status       int
	TemplateFile string
	Data         interface{}
}

Response handles the rendering

type Router

type Router struct {
	Mux             *chi.Mux          `json:"-"`
	LanguageMatcher language.Matcher  `json:"-"`
	RoutesSender    chan string       `json:"-"`
	RoutesReceiver  chan http.Handler `json:"-"`
	Middleware      `json:"middleware,omitempty"`
}

Router contains the router and all needed methods for automated translation

func (*Router) PrependMiddleware

func (r *Router) PrependMiddleware(router *chi.Mux)

PrependMiddleware is used to add basic middleware to routers

func (*Router) RegisterRoutes

func (r *Router) RegisterRoutes(languages map[string]int, server server, csp string)

RegisterRoutes handles routes and different languages

type Templates

type Templates struct {
	TemplateFolder string `json:"template_folder,omitempty"`
	BaseTemplate   string `json:"base_template,omitempty"`
	// contains filtered or unexported fields
}

Templates holds cached template files

func (*Templates) CacheFiles

func (t *Templates) CacheFiles(translation Translation) error

CacheFiles processes templates and saves them to the according map

type Translation

type Translation struct {
	Amount    int                 `json:"-"`
	Languages map[string]int      `json:"languages,omitempty"`
	Locales   map[string]string   `json:"locales,omitempty"`
	Phrases   map[string][]string `json:"phrases,omitempty"`
	URL       map[string][]string `json:"url,omitempty"`
}

Translation handles all the functionality and data for translating

func (Translation) Translate

func (t Translation) Translate(s, lang string) string

Translate phrase to according language

func (Translation) TranslateURL

func (t Translation) TranslateURL(s, lang string) string

TranslateURL phrase to URL friendly translation

Jump to

Keyboard shortcuts

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