templatefunc.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package beego
  15. import (
  16. "errors"
  17. "fmt"
  18. "html/template"
  19. "net/url"
  20. "reflect"
  21. "regexp"
  22. "strconv"
  23. "strings"
  24. "time"
  25. )
  26. // Substr returns the substr from start to length.
  27. func Substr(s string, start, length int) string {
  28. bt := []rune(s)
  29. if start < 0 {
  30. start = 0
  31. }
  32. if start > len(bt) {
  33. start = start % len(bt)
  34. }
  35. var end int
  36. if (start + length) > (len(bt) - 1) {
  37. end = len(bt)
  38. } else {
  39. end = start + length
  40. }
  41. return string(bt[start:end])
  42. }
  43. // HTML2str returns escaping text convert from html.
  44. func HTML2str(html string) string {
  45. src := string(html)
  46. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  47. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  48. //remove STYLE
  49. re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
  50. src = re.ReplaceAllString(src, "")
  51. //remove SCRIPT
  52. re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
  53. src = re.ReplaceAllString(src, "")
  54. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  55. src = re.ReplaceAllString(src, "\n")
  56. re, _ = regexp.Compile("\\s{2,}")
  57. src = re.ReplaceAllString(src, "\n")
  58. return strings.TrimSpace(src)
  59. }
  60. // DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat"
  61. func DateFormat(t time.Time, layout string) (datestring string) {
  62. datestring = t.Format(layout)
  63. return
  64. }
  65. // DateFormat pattern rules.
  66. var datePatterns = []string{
  67. // year
  68. "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  69. "y", "06", //A two digit representation of a year Examples: 99 or 03
  70. // month
  71. "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
  72. "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
  73. "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
  74. "F", "January", // A full textual representation of a month, such as January or March January through December
  75. // day
  76. "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
  77. "j", "2", // Day of the month without leading zeros 1 to 31
  78. // week
  79. "D", "Mon", // A textual representation of a day, three letters Mon through Sun
  80. "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
  81. // time
  82. "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
  83. "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
  84. "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
  85. "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
  86. "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
  87. "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
  88. "i", "04", // Minutes with leading zeros 00 to 59
  89. "s", "05", // Seconds, with leading zeros 00 through 59
  90. // time zone
  91. "T", "MST",
  92. "P", "-07:00",
  93. "O", "-0700",
  94. // RFC 2822
  95. "r", time.RFC1123Z,
  96. }
  97. // DateParse Parse Date use PHP time format.
  98. func DateParse(dateString, format string) (time.Time, error) {
  99. replacer := strings.NewReplacer(datePatterns...)
  100. format = replacer.Replace(format)
  101. return time.ParseInLocation(format, dateString, time.Local)
  102. }
  103. // Date takes a PHP like date func to Go's time format.
  104. func Date(t time.Time, format string) string {
  105. replacer := strings.NewReplacer(datePatterns...)
  106. format = replacer.Replace(format)
  107. return t.Format(format)
  108. }
  109. // Compare is a quick and dirty comparison function. It will convert whatever you give it to strings and see if the two values are equal.
  110. // Whitespace is trimmed. Used by the template parser as "eq".
  111. func Compare(a, b interface{}) (equal bool) {
  112. equal = false
  113. if strings.TrimSpace(fmt.Sprintf("%v", a)) == strings.TrimSpace(fmt.Sprintf("%v", b)) {
  114. equal = true
  115. }
  116. return
  117. }
  118. // CompareNot !Compare
  119. func CompareNot(a, b interface{}) (equal bool) {
  120. return !Compare(a, b)
  121. }
  122. // NotNil the same as CompareNot
  123. func NotNil(a interface{}) (isNil bool) {
  124. return CompareNot(a, nil)
  125. }
  126. // GetConfig get the Appconfig
  127. func GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error) {
  128. switch returnType {
  129. case "String":
  130. value = AppConfig.String(key)
  131. case "Bool":
  132. value, err = AppConfig.Bool(key)
  133. case "Int":
  134. value, err = AppConfig.Int(key)
  135. case "Int64":
  136. value, err = AppConfig.Int64(key)
  137. case "Float":
  138. value, err = AppConfig.Float(key)
  139. case "DIY":
  140. value, err = AppConfig.DIY(key)
  141. default:
  142. err = errors.New("Config keys must be of type String, Bool, Int, Int64, Float, or DIY")
  143. }
  144. if err != nil {
  145. if reflect.TypeOf(returnType) != reflect.TypeOf(defaultVal) {
  146. err = errors.New("defaultVal type does not match returnType")
  147. } else {
  148. value, err = defaultVal, nil
  149. }
  150. } else if reflect.TypeOf(value).Kind() == reflect.String {
  151. if value == "" {
  152. if reflect.TypeOf(defaultVal).Kind() != reflect.String {
  153. err = errors.New("defaultVal type must be a String if the returnType is a String")
  154. } else {
  155. value = defaultVal.(string)
  156. }
  157. }
  158. }
  159. return
  160. }
  161. // Str2html Convert string to template.HTML type.
  162. func Str2html(raw string) template.HTML {
  163. return template.HTML(raw)
  164. }
  165. // Htmlquote returns quoted html string.
  166. func Htmlquote(src string) string {
  167. //HTML编码为实体符号
  168. /*
  169. Encodes `text` for raw use in HTML.
  170. >>> htmlquote("<'&\\">")
  171. '&lt;&#39;&amp;&quot;&gt;'
  172. */
  173. text := string(src)
  174. text = strings.Replace(text, "&", "&amp;", -1) // Must be done first!
  175. text = strings.Replace(text, "<", "&lt;", -1)
  176. text = strings.Replace(text, ">", "&gt;", -1)
  177. text = strings.Replace(text, "'", "&#39;", -1)
  178. text = strings.Replace(text, "\"", "&quot;", -1)
  179. text = strings.Replace(text, "“", "&ldquo;", -1)
  180. text = strings.Replace(text, "”", "&rdquo;", -1)
  181. text = strings.Replace(text, " ", "&nbsp;", -1)
  182. return strings.TrimSpace(text)
  183. }
  184. // Htmlunquote returns unquoted html string.
  185. func Htmlunquote(src string) string {
  186. //实体符号解释为HTML
  187. /*
  188. Decodes `text` that's HTML quoted.
  189. >>> htmlunquote('&lt;&#39;&amp;&quot;&gt;')
  190. '<\\'&">'
  191. */
  192. // strings.Replace(s, old, new, n)
  193. // 在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换
  194. text := string(src)
  195. text = strings.Replace(text, "&nbsp;", " ", -1)
  196. text = strings.Replace(text, "&rdquo;", "”", -1)
  197. text = strings.Replace(text, "&ldquo;", "“", -1)
  198. text = strings.Replace(text, "&quot;", "\"", -1)
  199. text = strings.Replace(text, "&#39;", "'", -1)
  200. text = strings.Replace(text, "&gt;", ">", -1)
  201. text = strings.Replace(text, "&lt;", "<", -1)
  202. text = strings.Replace(text, "&amp;", "&", -1) // Must be done last!
  203. return strings.TrimSpace(text)
  204. }
  205. // URLFor returns url string with another registered controller handler with params.
  206. // usage:
  207. //
  208. // URLFor(".index")
  209. // print URLFor("index")
  210. // router /login
  211. // print URLFor("login")
  212. // print URLFor("login", "next","/"")
  213. // router /profile/:username
  214. // print UrlFor("profile", ":username","John Doe")
  215. // result:
  216. // /
  217. // /login
  218. // /login?next=/
  219. // /user/John%20Doe
  220. //
  221. // more detail http://beego.me/docs/mvc/controller/urlbuilding.md
  222. func URLFor(endpoint string, values ...interface{}) string {
  223. return BeeApp.Handlers.URLFor(endpoint, values...)
  224. }
  225. // AssetsJs returns script tag with src string.
  226. func AssetsJs(src string) template.HTML {
  227. text := string(src)
  228. text = "<script src=\"" + src + "\"></script>"
  229. return template.HTML(text)
  230. }
  231. // AssetsCSS returns stylesheet link tag with src string.
  232. func AssetsCSS(src string) template.HTML {
  233. text := string(src)
  234. text = "<link href=\"" + src + "\" rel=\"stylesheet\" />"
  235. return template.HTML(text)
  236. }
  237. // ParseForm will parse form values to struct via tag.
  238. // Support for anonymous struct.
  239. func parseFormToStruct(form url.Values, objT reflect.Type, objV reflect.Value) error {
  240. for i := 0; i < objT.NumField(); i++ {
  241. fieldV := objV.Field(i)
  242. if !fieldV.CanSet() {
  243. continue
  244. }
  245. fieldT := objT.Field(i)
  246. if fieldT.Anonymous && fieldT.Type.Kind() == reflect.Struct {
  247. err := parseFormToStruct(form, fieldT.Type, fieldV)
  248. if err != nil {
  249. return err
  250. }
  251. continue
  252. }
  253. tags := strings.Split(fieldT.Tag.Get("form"), ",")
  254. var tag string
  255. if len(tags) == 0 || len(tags[0]) == 0 {
  256. tag = fieldT.Name
  257. } else if tags[0] == "-" {
  258. continue
  259. } else {
  260. tag = tags[0]
  261. }
  262. value := form.Get(tag)
  263. if len(value) == 0 {
  264. continue
  265. }
  266. switch fieldT.Type.Kind() {
  267. case reflect.Bool:
  268. if strings.ToLower(value) == "on" || strings.ToLower(value) == "1" || strings.ToLower(value) == "yes" {
  269. fieldV.SetBool(true)
  270. continue
  271. }
  272. if strings.ToLower(value) == "off" || strings.ToLower(value) == "0" || strings.ToLower(value) == "no" {
  273. fieldV.SetBool(false)
  274. continue
  275. }
  276. b, err := strconv.ParseBool(value)
  277. if err != nil {
  278. return err
  279. }
  280. fieldV.SetBool(b)
  281. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  282. x, err := strconv.ParseInt(value, 10, 64)
  283. if err != nil {
  284. return err
  285. }
  286. fieldV.SetInt(x)
  287. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  288. x, err := strconv.ParseUint(value, 10, 64)
  289. if err != nil {
  290. return err
  291. }
  292. fieldV.SetUint(x)
  293. case reflect.Float32, reflect.Float64:
  294. x, err := strconv.ParseFloat(value, 64)
  295. if err != nil {
  296. return err
  297. }
  298. fieldV.SetFloat(x)
  299. case reflect.Interface:
  300. fieldV.Set(reflect.ValueOf(value))
  301. case reflect.String:
  302. fieldV.SetString(value)
  303. case reflect.Struct:
  304. switch fieldT.Type.String() {
  305. case "time.Time":
  306. format := time.RFC3339
  307. if len(tags) > 1 {
  308. format = tags[1]
  309. }
  310. t, err := time.ParseInLocation(format, value, time.Local)
  311. if err != nil {
  312. return err
  313. }
  314. fieldV.Set(reflect.ValueOf(t))
  315. }
  316. case reflect.Slice:
  317. if fieldT.Type == sliceOfInts {
  318. formVals := form[tag]
  319. fieldV.Set(reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(int(1))), len(formVals), len(formVals)))
  320. for i := 0; i < len(formVals); i++ {
  321. val, err := strconv.Atoi(formVals[i])
  322. if err != nil {
  323. return err
  324. }
  325. fieldV.Index(i).SetInt(int64(val))
  326. }
  327. } else if fieldT.Type == sliceOfStrings {
  328. formVals := form[tag]
  329. fieldV.Set(reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf("")), len(formVals), len(formVals)))
  330. for i := 0; i < len(formVals); i++ {
  331. fieldV.Index(i).SetString(formVals[i])
  332. }
  333. }
  334. }
  335. }
  336. return nil
  337. }
  338. // ParseForm will parse form values to struct via tag.
  339. func ParseForm(form url.Values, obj interface{}) error {
  340. objT := reflect.TypeOf(obj)
  341. objV := reflect.ValueOf(obj)
  342. if !isStructPtr(objT) {
  343. return fmt.Errorf("%v must be a struct pointer", obj)
  344. }
  345. objT = objT.Elem()
  346. objV = objV.Elem()
  347. return parseFormToStruct(form, objT, objV)
  348. }
  349. var sliceOfInts = reflect.TypeOf([]int(nil))
  350. var sliceOfStrings = reflect.TypeOf([]string(nil))
  351. var unKind = map[reflect.Kind]bool{
  352. reflect.Uintptr: true,
  353. reflect.Complex64: true,
  354. reflect.Complex128: true,
  355. reflect.Array: true,
  356. reflect.Chan: true,
  357. reflect.Func: true,
  358. reflect.Map: true,
  359. reflect.Ptr: true,
  360. reflect.Slice: true,
  361. reflect.Struct: true,
  362. reflect.UnsafePointer: true,
  363. }
  364. // RenderForm will render object to form html.
  365. // obj must be a struct pointer.
  366. func RenderForm(obj interface{}) template.HTML {
  367. objT := reflect.TypeOf(obj)
  368. objV := reflect.ValueOf(obj)
  369. if !isStructPtr(objT) {
  370. return template.HTML("")
  371. }
  372. objT = objT.Elem()
  373. objV = objV.Elem()
  374. var raw []string
  375. for i := 0; i < objT.NumField(); i++ {
  376. fieldV := objV.Field(i)
  377. if !fieldV.CanSet() || unKind[fieldV.Kind()] {
  378. continue
  379. }
  380. fieldT := objT.Field(i)
  381. label, name, fType, id, class, ignored, required := parseFormTag(fieldT)
  382. if ignored {
  383. continue
  384. }
  385. raw = append(raw, renderFormField(label, name, fType, fieldV.Interface(), id, class, required))
  386. }
  387. return template.HTML(strings.Join(raw, "</br>"))
  388. }
  389. // renderFormField returns a string containing HTML of a single form field.
  390. func renderFormField(label, name, fType string, value interface{}, id string, class string, required bool) string {
  391. if id != "" {
  392. id = " id=\"" + id + "\""
  393. }
  394. if class != "" {
  395. class = " class=\"" + class + "\""
  396. }
  397. requiredString := ""
  398. if required {
  399. requiredString = " required"
  400. }
  401. if isValidForInput(fType) {
  402. return fmt.Sprintf(`%v<input%v%v name="%v" type="%v" value="%v"%v>`, label, id, class, name, fType, value, requiredString)
  403. }
  404. return fmt.Sprintf(`%v<%v%v%v name="%v"%v>%v</%v>`, label, fType, id, class, name, requiredString, value, fType)
  405. }
  406. // isValidForInput checks if fType is a valid value for the `type` property of an HTML input element.
  407. func isValidForInput(fType string) bool {
  408. validInputTypes := strings.Fields("text password checkbox radio submit reset hidden image file button search email url tel number range date month week time datetime datetime-local color")
  409. for _, validType := range validInputTypes {
  410. if fType == validType {
  411. return true
  412. }
  413. }
  414. return false
  415. }
  416. // parseFormTag takes the stuct-tag of a StructField and parses the `form` value.
  417. // returned are the form label, name-property, type and wether the field should be ignored.
  418. func parseFormTag(fieldT reflect.StructField) (label, name, fType string, id string, class string, ignored bool, required bool) {
  419. tags := strings.Split(fieldT.Tag.Get("form"), ",")
  420. label = fieldT.Name + ": "
  421. name = fieldT.Name
  422. fType = "text"
  423. ignored = false
  424. id = fieldT.Tag.Get("id")
  425. class = fieldT.Tag.Get("class")
  426. required = false
  427. required_field := fieldT.Tag.Get("required")
  428. if required_field != "-" && required_field != "" {
  429. required, _ = strconv.ParseBool(required_field)
  430. }
  431. switch len(tags) {
  432. case 1:
  433. if tags[0] == "-" {
  434. ignored = true
  435. }
  436. if len(tags[0]) > 0 {
  437. name = tags[0]
  438. }
  439. case 2:
  440. if len(tags[0]) > 0 {
  441. name = tags[0]
  442. }
  443. if len(tags[1]) > 0 {
  444. fType = tags[1]
  445. }
  446. case 3:
  447. if len(tags[0]) > 0 {
  448. name = tags[0]
  449. }
  450. if len(tags[1]) > 0 {
  451. fType = tags[1]
  452. }
  453. if len(tags[2]) > 0 {
  454. label = tags[2]
  455. }
  456. }
  457. return
  458. }
  459. func isStructPtr(t reflect.Type) bool {
  460. return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
  461. }
  462. // go1.2 added template funcs. begin
  463. var (
  464. errBadComparisonType = errors.New("invalid type for comparison")
  465. errBadComparison = errors.New("incompatible types for comparison")
  466. errNoComparison = errors.New("missing argument for comparison")
  467. )
  468. type kind int
  469. const (
  470. invalidKind kind = iota
  471. boolKind
  472. complexKind
  473. intKind
  474. floatKind
  475. stringKind
  476. uintKind
  477. )
  478. func basicKind(v reflect.Value) (kind, error) {
  479. switch v.Kind() {
  480. case reflect.Bool:
  481. return boolKind, nil
  482. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  483. return intKind, nil
  484. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  485. return uintKind, nil
  486. case reflect.Float32, reflect.Float64:
  487. return floatKind, nil
  488. case reflect.Complex64, reflect.Complex128:
  489. return complexKind, nil
  490. case reflect.String:
  491. return stringKind, nil
  492. }
  493. return invalidKind, errBadComparisonType
  494. }
  495. // eq evaluates the comparison a == b || a == c || ...
  496. func eq(arg1 interface{}, arg2 ...interface{}) (bool, error) {
  497. v1 := reflect.ValueOf(arg1)
  498. k1, err := basicKind(v1)
  499. if err != nil {
  500. return false, err
  501. }
  502. if len(arg2) == 0 {
  503. return false, errNoComparison
  504. }
  505. for _, arg := range arg2 {
  506. v2 := reflect.ValueOf(arg)
  507. k2, err := basicKind(v2)
  508. if err != nil {
  509. return false, err
  510. }
  511. if k1 != k2 {
  512. return false, errBadComparison
  513. }
  514. truth := false
  515. switch k1 {
  516. case boolKind:
  517. truth = v1.Bool() == v2.Bool()
  518. case complexKind:
  519. truth = v1.Complex() == v2.Complex()
  520. case floatKind:
  521. truth = v1.Float() == v2.Float()
  522. case intKind:
  523. truth = v1.Int() == v2.Int()
  524. case stringKind:
  525. truth = v1.String() == v2.String()
  526. case uintKind:
  527. truth = v1.Uint() == v2.Uint()
  528. default:
  529. panic("invalid kind")
  530. }
  531. if truth {
  532. return true, nil
  533. }
  534. }
  535. return false, nil
  536. }
  537. // ne evaluates the comparison a != b.
  538. func ne(arg1, arg2 interface{}) (bool, error) {
  539. // != is the inverse of ==.
  540. equal, err := eq(arg1, arg2)
  541. return !equal, err
  542. }
  543. // lt evaluates the comparison a < b.
  544. func lt(arg1, arg2 interface{}) (bool, error) {
  545. v1 := reflect.ValueOf(arg1)
  546. k1, err := basicKind(v1)
  547. if err != nil {
  548. return false, err
  549. }
  550. v2 := reflect.ValueOf(arg2)
  551. k2, err := basicKind(v2)
  552. if err != nil {
  553. return false, err
  554. }
  555. if k1 != k2 {
  556. return false, errBadComparison
  557. }
  558. truth := false
  559. switch k1 {
  560. case boolKind, complexKind:
  561. return false, errBadComparisonType
  562. case floatKind:
  563. truth = v1.Float() < v2.Float()
  564. case intKind:
  565. truth = v1.Int() < v2.Int()
  566. case stringKind:
  567. truth = v1.String() < v2.String()
  568. case uintKind:
  569. truth = v1.Uint() < v2.Uint()
  570. default:
  571. panic("invalid kind")
  572. }
  573. return truth, nil
  574. }
  575. // le evaluates the comparison <= b.
  576. func le(arg1, arg2 interface{}) (bool, error) {
  577. // <= is < or ==.
  578. lessThan, err := lt(arg1, arg2)
  579. if lessThan || err != nil {
  580. return lessThan, err
  581. }
  582. return eq(arg1, arg2)
  583. }
  584. // gt evaluates the comparison a > b.
  585. func gt(arg1, arg2 interface{}) (bool, error) {
  586. // > is the inverse of <=.
  587. lessOrEqual, err := le(arg1, arg2)
  588. if err != nil {
  589. return false, err
  590. }
  591. return !lessOrEqual, nil
  592. }
  593. // ge evaluates the comparison a >= b.
  594. func ge(arg1, arg2 interface{}) (bool, error) {
  595. // >= is the inverse of <.
  596. lessThan, err := lt(arg1, arg2)
  597. if err != nil {
  598. return false, err
  599. }
  600. return !lessThan, nil
  601. }
  602. // MapGet getting value from map by keys
  603. // usage:
  604. // Data["m"] = map[string]interface{} {
  605. // "a": 1,
  606. // "1": map[string]float64{
  607. // "c": 4,
  608. // },
  609. // }
  610. //
  611. // {{ map_get m "a" }} // return 1
  612. // {{ map_get m 1 "c" }} // return 4
  613. func MapGet(arg1 interface{}, arg2 ...interface{}) (interface{}, error) {
  614. arg1Type := reflect.TypeOf(arg1)
  615. arg1Val := reflect.ValueOf(arg1)
  616. if arg1Type.Kind() == reflect.Map && len(arg2) > 0 {
  617. // check whether arg2[0] type equals to arg1 key type
  618. // if they are different, make conversion
  619. arg2Val := reflect.ValueOf(arg2[0])
  620. arg2Type := reflect.TypeOf(arg2[0])
  621. if arg2Type.Kind() != arg1Type.Key().Kind() {
  622. // convert arg2Value to string
  623. var arg2ConvertedVal interface{}
  624. arg2String := fmt.Sprintf("%v", arg2[0])
  625. // convert string representation to any other type
  626. switch arg1Type.Key().Kind() {
  627. case reflect.Bool:
  628. arg2ConvertedVal, _ = strconv.ParseBool(arg2String)
  629. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  630. arg2ConvertedVal, _ = strconv.ParseInt(arg2String, 0, 64)
  631. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  632. arg2ConvertedVal, _ = strconv.ParseUint(arg2String, 0, 64)
  633. case reflect.Float32, reflect.Float64:
  634. arg2ConvertedVal, _ = strconv.ParseFloat(arg2String, 64)
  635. case reflect.String:
  636. arg2ConvertedVal = arg2String
  637. default:
  638. arg2ConvertedVal = arg2Val.Interface()
  639. }
  640. arg2Val = reflect.ValueOf(arg2ConvertedVal)
  641. }
  642. storedVal := arg1Val.MapIndex(arg2Val)
  643. if storedVal.IsValid() {
  644. var result interface{}
  645. switch arg1Type.Elem().Kind() {
  646. case reflect.Bool:
  647. result = storedVal.Bool()
  648. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  649. result = storedVal.Int()
  650. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  651. result = storedVal.Uint()
  652. case reflect.Float32, reflect.Float64:
  653. result = storedVal.Float()
  654. case reflect.String:
  655. result = storedVal.String()
  656. default:
  657. result = storedVal.Interface()
  658. }
  659. // if there is more keys, handle this recursively
  660. if len(arg2) > 1 {
  661. return MapGet(result, arg2[1:]...)
  662. }
  663. return result, nil
  664. }
  665. return nil, nil
  666. }
  667. return nil, nil
  668. }