code.gitea.io/gitea@v1.22.3/modules/web/middleware/flash.go (about) 1 // Copyright 2020 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package middleware 5 6 import ( 7 "fmt" 8 "html/template" 9 "net/url" 10 ) 11 12 // Flash represents a one time data transfer between two requests. 13 type Flash struct { 14 DataStore ContextDataStore 15 url.Values 16 ErrorMsg, WarningMsg, InfoMsg, SuccessMsg string 17 } 18 19 func (f *Flash) set(name, msg string, current ...bool) { 20 if f.Values == nil { 21 f.Values = make(map[string][]string) 22 } 23 showInCurrentPage := len(current) > 0 && current[0] 24 if showInCurrentPage { 25 // assign it to the context data, then the template can use ".Flash.XxxMsg" to render the message 26 f.DataStore.GetData()["Flash"] = f 27 } else { 28 // the message map will be saved into the cookie and be shown in next response (a new page response which decodes the cookie) 29 f.Set(name, msg) 30 } 31 } 32 33 func flashMsgStringOrHTML(msg any) string { 34 switch v := msg.(type) { 35 case string: 36 return v 37 case template.HTML: 38 return string(v) 39 } 40 panic(fmt.Sprintf("unknown type: %T", msg)) 41 } 42 43 // Error sets error message 44 func (f *Flash) Error(msg any, current ...bool) { 45 f.ErrorMsg = flashMsgStringOrHTML(msg) 46 f.set("error", f.ErrorMsg, current...) 47 } 48 49 // Warning sets warning message 50 func (f *Flash) Warning(msg any, current ...bool) { 51 f.WarningMsg = flashMsgStringOrHTML(msg) 52 f.set("warning", f.WarningMsg, current...) 53 } 54 55 // Info sets info message 56 func (f *Flash) Info(msg any, current ...bool) { 57 f.InfoMsg = flashMsgStringOrHTML(msg) 58 f.set("info", f.InfoMsg, current...) 59 } 60 61 // Success sets success message 62 func (f *Flash) Success(msg any, current ...bool) { 63 f.SuccessMsg = flashMsgStringOrHTML(msg) 64 f.set("success", f.SuccessMsg, current...) 65 }