templatefunc.go 21 KB

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