github.com/res-am/buffalo@v0.11.1/flash.go (about)

     1  package buffalo
     2  
     3  import "encoding/json"
     4  
     5  // flashKey is the prefix inside the Session.
     6  const flashKey = "_flash_"
     7  
     8  //Flash is a struct that helps with the operations over flash messages.
     9  type Flash struct {
    10  	data map[string][]string
    11  }
    12  
    13  //Delete removes a particular key from the Flash.
    14  func (f Flash) Delete(key string) {
    15  	delete(f.data, key)
    16  }
    17  
    18  //Clear removes all keys from the Flash.
    19  func (f *Flash) Clear() {
    20  	f.data = map[string][]string{}
    21  }
    22  
    23  //Set allows to set a list of values into a particular key.
    24  func (f Flash) Set(key string, values []string) {
    25  	f.data[key] = values
    26  }
    27  
    28  //Add adds a flash value for a flash key, if the key already has values the list for that value grows.
    29  func (f Flash) Add(key, value string) {
    30  	if len(f.data[key]) == 0 {
    31  		f.data[key] = []string{value}
    32  		return
    33  	}
    34  
    35  	f.data[key] = append(f.data[key], value)
    36  }
    37  
    38  //Persist the flash inside the session.
    39  func (f Flash) persist(session *Session) {
    40  	b, _ := json.Marshal(f.data)
    41  	session.Set(flashKey, b)
    42  	session.Save()
    43  }
    44  
    45  //newFlash creates a new Flash and loads the session data inside its data.
    46  func newFlash(session *Session) *Flash {
    47  	result := &Flash{
    48  		data: map[string][]string{},
    49  	}
    50  
    51  	if session.Session != nil {
    52  		if f := session.Get(flashKey); f != nil {
    53  			json.Unmarshal(f.([]byte), &result.data)
    54  		}
    55  	}
    56  	return result
    57  }