go从0到1项目实战体系三十四:演示案列实例三

1. 知识点1:

(1). model文件中:

type BookMetas struct {
	...
}
func NewBookMeta(key string,value string,itemid int) *BookMetas  {
	return &BookMetas{MetaKey:key,MetaValue:value,ItemId:itemid}
}
func(this *BookMetas) Save() error {
	// 当主键冲突时,插入已存在主键的记录时,将插入操作变为修改
	return AppInit.GetDB().Set("gorm:insert_option",
		"ON DUPLICATE KEY UPDATE meta_value=meta_value+1").Create(this).Error
}

(2). service文件中:

Models.NewBookMeta("click","1",prods.BookID).Save():. NewBookMeta()返回的是一个*BookMetas.

2. service方法可自定义扩展返回值:

(1). endpoint文件:

type BookResponse struct {
	Result interface{} `json:"result"`
	Metas interface{} `json:"metas"`    // 追加一个值
}
// 图书详细
func BookDetailEndPoint(book *BookService)  App.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req:=request.(*BookDetailRequest)
		result, metas, err := book.LoadBookDetail(req)   // 接收3个值
		return &BookResponse{Result:result, Metas:metas}, err
	}
}

(2). service文件:

// 返回3个值
func(this *BookService) LoadBookDetail(req  *BookDetailRequest) (*Models.Books, []*Models.BookMetas, error) {
	prods:=&Models.Books{}
	if AppInit.GetDB().Find(prods,req.BookID).RowsAffected!=1{
		return nil, nil, fmt.Errorf("no book")
	}
    Models.NewBookMeta("click","1",prods.BookID).Save()
	metas:=[]*Models.BookMetas{}
	AppInit.GetDB().Where("item_id=?",prods.BookID).Find(&metas)
	return prods, metas, nil
}

你可能感兴趣的:(golang,开发语言,后端,gin,系统架构,微服务,性能优化)