Cache

Go-Mojito provides an easy to use interface for caching and provides a basic in-memory cache implementation which is sufficient for small amounts of data.

How to use Caches

This example will show you how to use the mojito.Cache interface to cache your data.

package main

import (
	"time"

	"github.com/go-mojito/mojito"
	"github.com/go-mojito/mojito/log"
)

var address = "0.0.0.0:8123"
var cacheKey = "greeting"

func main() {
	mojito.GET("/", helloHandler)
	mojito.GET("/:name", setHelloHandler)

	log.Infof("Server has started on %s", address)
	log.Error(mojito.ListenAndServe(address))
}

func helloHandler(cache mojito.Cache, ctx mojito.Context) {
	var greeting string
	cache.GetOrDefault(cacheKey, &greeting, "world")
	ctx.String("Hello " + greeting + "!")
}

func setHelloHandler(cache mojito.Cache, ctx mojito.Context) {
	cache.Set(cacheKey, ctx.Request().Param("name"))
	cache.ExpireAfter(cacheKey, time.Minute*5)
	ctx.String("A new greeting has been set :D")
}