templatefunc.go 20 KB

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