github.com/naoina/kocha@v0.7.1-0.20171129072645-78c7a531f799/flash.go (about)

     1  package kocha
     2  
     3  // Flash represents a container of flash messages.
     4  // Flash is for the one-time messaging between requests. It useful for
     5  // implementing the Post/Redirect/Get pattern.
     6  type Flash map[string]FlashData
     7  
     8  // Get gets a value associated with the given key.
     9  // If there is the no value associated with the key, Get returns "".
    10  func (f Flash) Get(key string) string {
    11  	if f == nil {
    12  		return ""
    13  	}
    14  	data, exists := f[key]
    15  	if !exists {
    16  		return ""
    17  	}
    18  	data.Loaded = true
    19  	f[key] = data
    20  	return data.Data
    21  }
    22  
    23  // Set sets the value associated with key.
    24  // It replaces the existing value associated with key.
    25  func (f Flash) Set(key, value string) {
    26  	if f == nil {
    27  		return
    28  	}
    29  	data := f[key]
    30  	data.Loaded = false
    31  	data.Data = value
    32  	f[key] = data
    33  }
    34  
    35  // Len returns a length of the dataset.
    36  func (f Flash) Len() int {
    37  	return len(f)
    38  }
    39  
    40  // deleteLoaded delete the loaded data.
    41  func (f Flash) deleteLoaded() {
    42  	for k, v := range f {
    43  		if v.Loaded {
    44  			delete(f, k)
    45  		}
    46  	}
    47  }
    48  
    49  // FlashData represents a data of flash messages.
    50  type FlashData struct {
    51  	Data   string // flash message.
    52  	Loaded bool   // whether the message was loaded.
    53  }