github.com/gogf/gf/v2@v2.7.4/util/gtag/gtag_func.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gtag 8 9 import ( 10 "regexp" 11 12 "github.com/gogf/gf/v2/errors/gerror" 13 ) 14 15 var ( 16 data = make(map[string]string) 17 regex = regexp.MustCompile(`\{(.+?)\}`) 18 ) 19 20 // Set sets tag content for specified name. 21 // Note that it panics if `name` already exists. 22 func Set(name, value string) { 23 if _, ok := data[name]; ok { 24 panic(gerror.Newf(`value for tag name "%s" already exists`, name)) 25 } 26 data[name] = value 27 } 28 29 // SetOver performs as Set, but it overwrites the old value if `name` already exists. 30 func SetOver(name, value string) { 31 data[name] = value 32 } 33 34 // Sets sets multiple tag content by map. 35 func Sets(m map[string]string) { 36 for k, v := range m { 37 Set(k, v) 38 } 39 } 40 41 // SetsOver performs as Sets, but it overwrites the old value if `name` already exists. 42 func SetsOver(m map[string]string) { 43 for k, v := range m { 44 SetOver(k, v) 45 } 46 } 47 48 // Get retrieves and returns the stored tag content for specified name. 49 func Get(name string) string { 50 return data[name] 51 } 52 53 // Parse parses and returns the content by replacing all tag name variable to 54 // its content for given `content`. 55 // Eg: 56 // gtag.Set("demo", "content") 57 // Parse(`This is {demo}`) -> `This is content`. 58 func Parse(content string) string { 59 return regex.ReplaceAllStringFunc(content, func(s string) string { 60 if v, ok := data[s[1:len(s)-1]]; ok { 61 return v 62 } 63 return s 64 }) 65 }