diff --git a/stringx/string_example_test.go b/stringx/string_example_test.go new file mode 100644 index 0000000..80ea91c --- /dev/null +++ b/stringx/string_example_test.go @@ -0,0 +1,36 @@ +// Copyright 2021 ecodeclub +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package stringx_test + +import ( + "fmt" + + "github.com/ecodeclub/ekit/stringx" +) + +func ExampleUnsafeToBytes() { + str := "hello" + val := stringx.UnsafeToBytes(str) + fmt.Println(len(val)) + // Output: + // 5 +} + +func ExampleUnsafeToString() { + val := stringx.UnsafeToString([]byte("hello")) + fmt.Println(val) + // Output: + // hello +} diff --git a/value.go b/value.go index e9c74bd..66108e1 100644 --- a/value.go +++ b/value.go @@ -15,6 +15,7 @@ package ekit import ( + "encoding/json" "errors" "reflect" "strconv" @@ -547,3 +548,12 @@ func (av AnyValue) BoolOrDefault(def bool) bool { } return val } + +// JSONScan 将 val 转化为一个对象 +func (av AnyValue) JSONScan(val any) error { + data, err := av.AsBytes() + if err != nil { + return err + } + return json.Unmarshal(data, val) +} diff --git a/value_test.go b/value_test.go index dac9982..46cec5a 100644 --- a/value_test.go +++ b/value_test.go @@ -1828,3 +1828,45 @@ func TestAnyValue_AsString(t *testing.T) { }) } } + +func TestAnyValue_JSONScan(t *testing.T) { + testCases := []struct { + name string + + av AnyValue + + wantUser User + wantErr error + }{ + { + name: "OK", + av: AnyValue{ + Val: `{"name": "Tom"}`, + }, + wantUser: User{ + Name: "Tom", + }, + }, + + { + name: "error", + av: AnyValue{ + Err: errors.New("mock error"), + }, + wantErr: errors.New("mock error"), + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var u User + err := tc.av.JSONScan(&u) + assert.Equal(t, tc.wantErr, err) + assert.Equal(t, tc.wantUser, u) + }) + } +} + +type User struct { + Name string `json:"name"` +}