Fix toggling on/off of Redis at runtime

This commit is contained in:
Noah 2017-12-23 13:32:26 -08:00
parent c03a010696
commit 3f7b800423
2 changed files with 25 additions and 3 deletions

View File

@ -1,10 +1,13 @@
package core package core
import ( import (
"fmt"
"net/http" "net/http"
"strconv" "strconv"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/kirsle/blog/core/caches/null"
"github.com/kirsle/blog/core/caches/redis"
"github.com/kirsle/blog/core/forms" "github.com/kirsle/blog/core/forms"
"github.com/kirsle/blog/core/models/settings" "github.com/kirsle/blog/core/models/settings"
"github.com/urfave/negroni" "github.com/urfave/negroni"
@ -43,12 +46,12 @@ func (b *Blog) SettingsHandler(w http.ResponseWriter, r *http.Request) {
Title: r.FormValue("title"), Title: r.FormValue("title"),
AdminEmail: r.FormValue("admin-email"), AdminEmail: r.FormValue("admin-email"),
URL: r.FormValue("url"), URL: r.FormValue("url"),
RedisEnabled: r.FormValue("redis-enabled") == "true", RedisEnabled: len(r.FormValue("redis-enabled")) > 0,
RedisHost: r.FormValue("redis-host"), RedisHost: r.FormValue("redis-host"),
RedisPort: redisPort, RedisPort: redisPort,
RedisDB: redisDB, RedisDB: redisDB,
RedisPrefix: r.FormValue("redis-prefix"), RedisPrefix: r.FormValue("redis-prefix"),
MailEnabled: r.FormValue("mail-enabled") == "true", MailEnabled: len(r.FormValue("mail-enabled")) > 0,
MailSender: r.FormValue("mail-sender"), MailSender: r.FormValue("mail-sender"),
MailHost: r.FormValue("mail-host"), MailHost: r.FormValue("mail-host"),
MailPort: mailPort, MailPort: mailPort,
@ -78,6 +81,25 @@ func (b *Blog) SettingsHandler(w http.ResponseWriter, r *http.Request) {
} else { } else {
// Save the settings. // Save the settings.
settings.Save() settings.Save()
// Reset Redis configuration.
if settings.Redis.Enabled {
cache, err := redis.New(
fmt.Sprintf("%s:%d", settings.Redis.Host, settings.Redis.Port),
settings.Redis.DB,
settings.Redis.Prefix,
)
if err != nil {
b.Flash(w, r, "Error connecting to Redis: %s", err)
b.Cache = null.New()
} else {
b.Cache = cache
}
} else {
b.Cache = null.New()
}
b.DB.Cache = b.Cache
b.FlashAndReload(w, r, "Settings have been saved!") b.FlashAndReload(w, r, "Settings have been saved!")
return return
} }

View File

@ -115,7 +115,7 @@ func (b *Blog) Pygmentize(language, source string) (string, error) {
cacheKey := "pygmentize:" + hash cacheKey := "pygmentize:" + hash
// Do we have it cached? // Do we have it cached?
if cached, err := b.Cache.Get(cacheKey); err == nil { if cached, err := b.Cache.Get(cacheKey); err == nil && len(cached) > 0 {
return string(cached), nil return string(cached), nil
} }