本文主要介绍 jinzhu/copier 的使用和常用场景

简介

在go后端项目开发中,内部rpc服务返回的字段跟api服务相差无几,一个个赋值比较费事儿。那么就需要Object、List、HashMap 等进行值拷贝。jinzhu/copier即提供了这些场景的支持。

copier 特性

  • 从方法复制到具有相同名称的字段
  • 从字段复制到具有相同名称的方法
  • 从一个切片复制到另一个切片
  • 从结构体复制到切片
  • 从map复制到map
  • 强制复制带有标记的字段
  • 忽略带有标记的字段
  • 深拷贝

Usage

Copy from struct

package main

import (
	"github.com/jinzhu/copier"
	"testing"
)

type User struct {
	Name         string
	Role         string
	Age          int32
	EmployeeCode int64 `copier:"EmployeeNum"` // specify field name

	// Explicitly ignored in the destination struct.
	Salary int
}

//目标结构体中的标签提供了copy指令。复制忽略
//或强制复制,如果字段没有被复制则惊慌或返回错误。
type Employee struct {
	//告诉copier。如果没有复制此字段,则复制到panic。
	Name string `copier:"must"`

	//告诉copier。 如果没有复制此字段,则返回错误。
	Age int32 `copier:"must,nopanic"`

	// 告诉copier。 显式忽略复制此字段。
	Salary int `copier:"-"`

	DoubleAge  int32
	EmployeeId int64 `copier:"EmployeeNum"` // 指定字段名
	SuperRole  string
}

func TestCopyStruct(t *testing.T) {
	var (
		user     = User{Name: "Jinzhu", Age: 18, Role: "Admin", Salary: 200000}
		employee = Employee{Salary: 150000}
	)
	copier.Copy(&employee, &user)
	t.Logf("%#v \n", employee)
}

output:

    copier_test.go:47: main.Employee{Name:"Jinzhu", Age:18, Salary:150000, DoubleAge:36, EmployeeId:0, SuperRole:"Super Admin"} 

Copy from slice to slice

func TestCopySlice(t *testing.T) {
	var (
		users     = []User{{Name: "Jinzhu", Age: 18, Role: "Admin", Salary: 100000}, {Name: "jinzhu 2", Age: 30, Role: "Dev", Salary: 60000}}
		employees = []Employee{}
	)
	employees = []Employee{}
	copier.Copy(&employees, &users)

	t.Logf("%#v \n", employees)
}`

output :

    copier_test.go:57: []main.Employee{main.Employee{Name:"Jinzhu", Age:18, Salary:0, DoubleAge:36, EmployeeId:0, SuperRole:"Super Admin"}, main.Employee{Name:"jinzhu 2", Age:30, Salary:0, DoubleAge:60, EmployeeId:0, SuperRole:"Super Dev"}} 

Copy from Map to Map

func TestCopyMap(t *testing.T) {
	// Copy map to map
	map1 := map[int]int{3: 6, 4: 8}
	map2 := map[int32]int8{}
	copier.Copy(&map2, map1)

	t.Logf("%#v \n", map2)
}

output :

    copier_test.go:66: map[int32]int8{3:6, 4:8} 

场景 1(rpc&api)

实际开发中,免不了服务间通讯,比较前文所说的场景,一个内部的rpc服务返回的参数和api服务差不多,那么就可以使用copier。

//伪代码如下
func ApiLogin(ctx context.Context,request *api.LoginRequest)(reply *api.LogingReply,err error)  {
	grpcClient := v1.NewGameGrpcClient(ctx)
	reply, err := client.Login(ctx, &grpc.api.LoginRequest{ 
					})
	user := api.LogingReply.User{}
 	copier.Copy(&user, reply.User())
return &api.LoginReply{
	User:user,
},err

场景 2 (model-object/aggregate)

实际开发中,不管是mvc\ddd 都会有从model到object/aggreate的repository,那么就可以使用copier。

func (r *UserRepo) Get(ctx context.Context, uid int64) (u User,err error) {
	model, err := db.User.Get(ctx, uid)
	if err != nil {
		return
	}
	obj:= User{}
	copy(&obj,model)
	return obj,nil
}

小结

copier提供不同类型之间相同的字段名,使用tag或者方法支持不同的字段名的赋值。减少一些重复的工作量,小巧实用。

参考

本文主要介绍 在go开发中 errors 的处理和第三方库 github.com/pkg/errors 的使用。

error interface

官方定义:

// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
	Error() string
}

常用的声明方式

//方式一
err1 := fmt.Errorf("io.EOF")
//方式二
err2 := errors.New("io.EOF")
//方式三: 实现interface
type err3 struct{
}
func (e err3) Error() string {
	return "err3"
}

go的错误常见是把错误层层传递,这样可能带来一些不友好的地方:

  • 错误判断,经过层次包裹的错误,使用层不好判断真实错误
  • 定位错误,error库过于简单,没有提供粗错误堆栈,不好定位问题

错误判断

常见错误的判断方式是:


type base struct{}

func (e base) Error() string {
	return "base error"
}

func wrapBase() error {
	return fmt.Errorf("wrapBase: %w", base{})
}

func TestErrors(t *testing.T) {
	t.Run("==", func(t *testing.T) {
		foo := &base{}
		bar := &base{}
		t.Log(foo)
		t.Log(bar)
		t.Log(foo == bar)
		assert.True(t, foo == bar)
	})
	t.Run("断言", func(t *testing.T) {
		var err error
		_, ok := err.(*base)
		assert.False(t, ok)
	})
	t.Run("Is", func(t *testing.T) {
		foo := base{}
		wrapFoo := wrapBase()
		assert.False(t, foo == wrapFoo)
		assert.True(t, errors.Is(wrapFoo, foo))
		assert.False(t, errors.Is(wrapFoo, &base{}))
	})
	t.Run("As", func(t *testing.T) {
		foo := base{}
		wrapFoo := wrapBase()
		assert.False(t, foo == wrapFoo)
		assert.True(t, errors.As(wrapFoo, &base{}))
	})
}

OutPut:

--- PASS: TestErrors (0.00s)
--- PASS: TestErrors/== (0.00s)
--- PASS: TestErrors/断言 (0.00s)
--- PASS: TestErrors/Is (0.00s)
 --- PASS: TestErrors/As (0.00s)
  • 当没有嵌套错误,可以使用 ==来判断;
  • 当有多层嵌套,可以使用 Is() :
    • //一个错误被认为匹配一个目标,如果它等于那个目标或如果它实现了一个方法Is(error) bool,使Is(target)返回true。
    • // As在err’s chain中找到第一个与target匹配的错误,如果找到,则设置指向错误值并返回true。否则,返回false

定位错误

常用的第三方库

github.com/pkg/errors/errors.go 提供了以下功能:

  • WithStack 包装堆栈
  • WithMessagef 包装异常
func TestWithStackCompare(t *testing.T) {
	t.Run("fmt.Errorf,无堆栈,不好定位", func(t *testing.T) {
		err1 := fmt.Errorf("io.EOF")
		fmt.Printf("err1: %+v", err1)
	})
	t.Run("errors ,无堆栈,不好定位", func(t *testing.T) {
		err2 := errors.New("io.EOF")
		fmt.Printf("err2: %+v", err2)
	})
	t.Run("pkgerrors,有堆栈,方便定位", func(t *testing.T) {
		err3 := pkgerrors.WithStack(io.EOF)
		fmt.Printf("err3: %+v", err3)
	})

}

OutPut:

=== RUN   TestWithStackCompare
=== RUN   TestWithStackCompare/fmt.Errorf,无堆栈,不好定位
err1: io.EOF=== RUN   TestWithStackCompare/errors_,无堆栈,不好定位
err2: io.EOF=== RUN   TestWithStackCompare/pkgerrors,有堆栈,便以定位
err3: EOF
tkingo.vip/egs/goerrors-demo.TestWithStackCompare.func3
	$ workspace/goerrors-demo/errors_test.go:113
testing.tRunner
	$ workspace/Go/src/testing/testing.go:1439
runtime.goexit

func TestWithMessagef(t *testing.T) {
	tests := []struct {
		err     error
		message string
		want    string
	}{
		{io.EOF, "read error", "read error: EOF"},
		{pkgerrors.WithMessagef(io.EOF, "read error without format specifier"), "client error", "client error: read error without format specifier: EOF"},
		{pkgerrors.WithMessagef(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
	}

	for _, tt := range tests {
		got := pkgerrors.WithMessagef(tt.err, tt.message).Error()
		if got != tt.want {
			t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
		}
	}
}

总结

pkg errors 应该能够支持错误堆栈、不同的打印格式很好的补充了go errors 的一些短板

参考:

  • github.com/pkg/errors

本文主要介绍一个好用的时间工具库,主要功能:

  • 当前时间
  • 修改地区
  • 解析字符串 等

Usage


import "github.com/jinzhu/now"

time.Now() // 2013-11-18 17:51:49.123456789 Mon

now.BeginningOfMinute()        // 2013-11-18 17:51:00 Mon
now.BeginningOfHour()          // 2013-11-18 17:00:00 Mon
now.BeginningOfDay()           // 2013-11-18 00:00:00 Mon
now.BeginningOfWeek()          // 2013-11-17 00:00:00 Sun
now.BeginningOfMonth()         // 2013-11-01 00:00:00 Fri
now.BeginningOfQuarter()       // 2013-10-01 00:00:00 Tue
now.BeginningOfYear()          // 2013-01-01 00:00:00 Tue

now.EndOfMinute()              // 2013-11-18 17:51:59.999999999 Mon
now.EndOfHour()                // 2013-11-18 17:59:59.999999999 Mon
now.EndOfDay()                 // 2013-11-18 23:59:59.999999999 Mon
now.EndOfWeek()                // 2013-11-23 23:59:59.999999999 Sat
now.EndOfMonth()               // 2013-11-30 23:59:59.999999999 Sat
now.EndOfQuarter()             // 2013-12-31 23:59:59.999999999 Tue
now.EndOfYear()                // 2013-12-31 23:59:59.999999999 Tue

now.WeekStartDay = time.Monday // Set Monday as first day, default is Sunday
now.EndOfWeek()                // 2013-11-24 23:59:59.999999999 Sun

修改地区

location, err := time.LoadLocation("Asia/Shanghai")

myConfig := &now.Config{
	WeekStartDay: time.Monday,
	TimeLocation: location,
	TimeFormats: []string{"2006-01-02 15:04:05"},
}

t := time.Date(2013, 11, 18, 17, 51, 49, 123456789, time.Now().Location()) // // 2013-11-18 17:51:49.123456789 Mon
myConfig.With(t).BeginningOfWeek()         // 2013-11-18 00:00:00 Mon

myConfig.Parse("2002-10-12 22:14:01")     // 2002-10-12 22:14:01
myConfig.Parse("2002-10-12 22:14")        // returns error 'can't parse string as time: 2002-10-12 22:14'

解析字符串

time.Now() // 2013-11-18 17:51:49.123456789 Mon

// Parse(string) (time.Time, error)
t, err := now.Parse("2017")                // 2017-01-01 00:00:00, nil
t, err := now.Parse("2017-10")             // 2017-10-01 00:00:00, nil
t, err := now.Parse("2017-10-13")          // 2017-10-13 00:00:00, nil
t, err := now.Parse("1999-12-12 12")       // 1999-12-12 12:00:00, nil
t, err := now.Parse("1999-12-12 12:20")    // 1999-12-12 12:20:00, nil
t, err := now.Parse("1999-12-12 12:20:21") // 1999-12-12 12:20:21, nil
t, err := now.Parse("10-13")               // 2013-10-13 00:00:00, nil
t, err := now.Parse("12:20")               // 2013-11-18 12:20:00, nil
t, err := now.Parse("12:20:13")            // 2013-11-18 12:20:13, nil
t, err := now.Parse("14")                  // 2013-11-18 14:00:00, nil
t, err := now.Parse("99:99")               // 2013-11-18 12:20:00, Can't parse string as time: 99:99`

参考

jefffff

Stay hungry. Stay Foolish COOL

Go backend developer

China Amoy