Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AnyValue: 增加 JSONScan 方法 #243

Merged
merged 1 commit into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions stringx/string_example_test.go
Original file line number Diff line number Diff line change
@@ -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
}
10 changes: 10 additions & 0 deletions value.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package ekit

import (
"encoding/json"
"errors"
"reflect"
"strconv"
Expand Down Expand Up @@ -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)
}
42 changes: 42 additions & 0 deletions value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Loading