Skip to content

Commit

Permalink
Merge pull request #17 from bavix/pkg-units
Browse files Browse the repository at this point in the history
[2.0] add pkg unit
  • Loading branch information
rez1dent3 committed Sep 1, 2023
2 parents c8415a8 + 577e2d9 commit 9c73a20
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 13 deletions.
5 changes: 2 additions & 3 deletions pkg/yaml2json/template.go → pkg/yaml2json/convertor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ package yaml2json

import (
"github.com/goccy/go-yaml"
"github.com/tokopedia/gripmock/pkg/template"
)

type Convertor struct {
engine *template.Engine
engine *engine
}

func New() *Convertor {
return &Convertor{engine: template.New()}
return &Convertor{engine: &engine{}}
}

func (t *Convertor) Execute(name string, data []byte) ([]byte, error) {
Expand Down
26 changes: 26 additions & 0 deletions pkg/yaml2json/convertor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package yaml2json_test

import (
"github.com/stretchr/testify/require"
"github.com/tokopedia/gripmock/pkg/yaml2json"
"testing"
)

func TestConvertor(t *testing.T) {
convertor := yaml2json.New()

bytes, err := convertor.Execute("hello", []byte(`
yaml2json:
base64: {{ uuidToBase64StdEncoding "77465064-a0ce-48a3-b7e4-d50f88e55093" }}
highLow: {{ uuidToHighLowLittleEndian "e351220b-4847-42f5-8abb-c052b87ff2d4" }}
`))

expected := `{
"yaml2json": {
"base64": "d0ZQZKDOSKO35NUPiOVQkw==",
"highLow": {"high":-773977811204288029,"low":-3102276763665777782}
}
}`
require.NoError(t, err)
require.JSONEq(t, expected, string(bytes))
}
18 changes: 8 additions & 10 deletions pkg/template/engine.go → pkg/yaml2json/engine.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package template
package yaml2json

import (
"bytes"
Expand All @@ -9,13 +9,9 @@ import (
"github.com/google/uuid"
)

type Engine struct{}
type engine struct{}

func New() *Engine {
return &Engine{}
}

func (e *Engine) Execute(name string, data []byte) ([]byte, error) {
func (e *engine) Execute(name string, data []byte) ([]byte, error) {
var buffer bytes.Buffer

parse, err := template.New(name).Funcs(e.funcMap()).Parse(string(data))
Expand All @@ -30,10 +26,12 @@ func (e *Engine) Execute(name string, data []byte) ([]byte, error) {
return buffer.Bytes(), nil
}

func (e *Engine) funcMap() template.FuncMap {
func (e *engine) funcMap() template.FuncMap {
return template.FuncMap{
"base64StdEncoding": func(str string) string {
return base64.StdEncoding.EncodeToString([]byte(str))
"uuidToBase64StdEncoding": func(guid string) string {
v := uuid.MustParse(guid)

return base64.StdEncoding.EncodeToString(v[:])
},
"uuidToHighLowLittleEndian": func(guid string) string {
v := uuid.MustParse(guid)
Expand Down

0 comments on commit 9c73a20

Please sign in to comment.