X-Git-Url: https://gerrit.akraino.org/r/gitweb?a=blobdiff_plain;f=src%2Ffoundation%2Fapi%2Frevel%2Fflash.go;fp=src%2Ffoundation%2Fapi%2Frevel%2Fflash.go;h=b27f5e061fd9f8cfdb580d2c35c4f83a44dcd7ef;hb=1d1ee6961c93781e1187d8c7faa868da6b2f01f4;hp=0000000000000000000000000000000000000000;hpb=56dd5e0f2164b37b40ac1daa188ccc618b4cbd19;p=iec.git diff --git a/src/foundation/api/revel/flash.go b/src/foundation/api/revel/flash.go new file mode 100644 index 0000000..b27f5e0 --- /dev/null +++ b/src/foundation/api/revel/flash.go @@ -0,0 +1,78 @@ +// Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved. +// Revel Framework source code and usage is governed by a MIT style +// license that can be found in the LICENSE file. + +package revel + +import ( + "fmt" + "net/http" + "net/url" +) + +// Flash represents a cookie that is overwritten on each request. +// It allows data to be stored across one page at a time. +// This is commonly used to implement success or error messages. +// E.g. the Post/Redirect/Get pattern: +// http://en.wikipedia.org/wiki/Post/Redirect/Get +type Flash struct { + // `Data` is the input which is read in `restoreFlash`, `Out` is the output which is set in a FLASH cookie at the end of the `FlashFilter()` + Data, Out map[string]string +} + +// Error serializes the given msg and args to an "error" key within +// the Flash cookie. +func (f Flash) Error(msg string, args ...interface{}) { + if len(args) == 0 { + f.Out["error"] = msg + } else { + f.Out["error"] = fmt.Sprintf(msg, args...) + } +} + +// Success serializes the given msg and args to a "success" key within +// the Flash cookie. +func (f Flash) Success(msg string, args ...interface{}) { + if len(args) == 0 { + f.Out["success"] = msg + } else { + f.Out["success"] = fmt.Sprintf(msg, args...) + } +} + +// FlashFilter is a Revel Filter that retrieves and sets the flash cookie. +// Within Revel, it is available as a Flash attribute on Controller instances. +// The name of the Flash cookie is set as CookiePrefix + "_FLASH". +func FlashFilter(c *Controller, fc []Filter) { + c.Flash = restoreFlash(c.Request) + c.ViewArgs["flash"] = c.Flash.Data + + fc[0](c, fc[1:]) + + // Store the flash. + var flashValue string + for key, value := range c.Flash.Out { + flashValue += "\x00" + key + ":" + value + "\x00" + } + c.SetCookie(&http.Cookie{ + Name: CookiePrefix + "_FLASH", + Value: url.QueryEscape(flashValue), + HttpOnly: true, + Secure: CookieSecure, + Path: "/", + }) +} + +// restoreFlash deserializes a Flash cookie struct from a request. +func restoreFlash(req *Request) Flash { + flash := Flash{ + Data: make(map[string]string), + Out: make(map[string]string), + } + if cookie, err := req.Cookie(CookiePrefix + "_FLASH"); err == nil { + ParseKeyValueCookie(cookie.GetValue(), func(key, val string) { + flash.Data[key] = val + }) + } + return flash +}