Skip to content

Commit

Permalink
Merge pull request #212 from jrasell/gh_209
Browse files Browse the repository at this point in the history
Add additional template funcs to allow parsing of types.
  • Loading branch information
jrasell committed Jul 13, 2018
2 parents 3bc5011 + a573d18 commit 8f92c84
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions template/funcs.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package template

import (
"encoding/json"
"errors"
"fmt"
"strconv"
"text/template"
"time"

Expand All @@ -18,6 +20,11 @@ func funcMap(consulClient *consul.Client) template.FuncMap {
"consulKeyExists": consulKeyExistsFunc(consulClient),
"consulKeyOrDefault": consulKeyOrDefaultFunc(consulClient),
"loop": loop,
"parseBool": parseBool,
"parseFloat": parseFloat,
"parseInt": parseInt,
"parseJSON": parseJSON,
"parseUint": parseUint,
"timeNow": timeNowFunc,
"timeNowUTC": timeNowUTCFunc,
"timeNowTimezone": timeNowTimezoneFunc(),
Expand Down Expand Up @@ -120,6 +127,66 @@ func loop(ints ...int64) (<-chan int64, error) {
return ch, nil
}

func parseBool(s string) (bool, error) {
if s == "" {
return false, nil
}

result, err := strconv.ParseBool(s)
if err != nil {
return false, err
}
return result, nil
}

func parseFloat(s string) (float64, error) {
if s == "" {
return 0.0, nil
}

result, err := strconv.ParseFloat(s, 10)
if err != nil {
return 0, err
}
return result, nil
}

func parseInt(s string) (int64, error) {
if s == "" {
return 0, nil
}

result, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
return result, nil
}

func parseJSON(s string) (interface{}, error) {
if s == "" {
return map[string]interface{}{}, nil
}

var data interface{}
if err := json.Unmarshal([]byte(s), &data); err != nil {
return nil, err
}
return data, nil
}

func parseUint(s string) (uint64, error) {
if s == "" {
return 0, nil
}

result, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return 0, err
}
return result, nil
}

func timeNowFunc() string {
return time.Now().Format("2006-01-02T15:04:05Z07:00")
}
Expand Down

0 comments on commit 8f92c84

Please sign in to comment.