教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang mapstructure 转出为空的问题

golang mapstructure 转出为空的问题

发布时间:2023-01-22   编辑:jiaochengji.com
教程集为您提供golang mapstructure 转出为空的问题等资源,欢迎您收藏本站,我们将为您提供最新的golang mapstructure 转出为空的问题资源
//struct映射
func (s *commentRedisStore) CommentMapToStruct(commentInfo *model.CommentInfo, mapValue map[string]string) error {
	if len(mapValue) == 0 {
		return errors.New("len(mapValue) == 0")
	}

	decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
		WeaklyTypedInput: true,
		Result:           commentInfo,
	})
	_ = decoder.Decode(mapValue)

	//重填时间
	if mapValue["createdAt"] != "" {
		timeStr := mapValue["createdAt"]
		commentInfo.CreatedAt, _ = time.Parse("2006-01-02T15:04:05Z07:00", timeStr)
	}
	if mapValue["updatedAt"] != "" {
		timeStr := mapValue["updatedAt"]
		commentInfo.UpdatedAt, _ = time.Parse("2006-01-02T15:04:05Z07:00", timeStr)
	}
	if mapValue["deletedAt"] != "" {
		timeStr := mapValue["deletedAt"]
		deletedAt, _ := time.Parse("2006-01-02T15:04:05Z07:00", timeStr)
		commentInfo.DeletedAt = &deletedAt
	} else {
		commentInfo.DeletedAt = nil
	}

	return nil
}

type CommentInfo struct {
	SN int64  `json:"sn"`
	ID string `gorm:"-" json:"id"` // 评论外部编号

	ArticleSN int64  `json:"articleSN"`
	ArticleID string `gorm:"-" json:"articleID"` // 文章外部编号

	UserID int `json:"userID"` // 用户id

	Content string `json:"content"` // 评论内容

	ReplyTo int `json:"replyTo"` // 被评论人id

	ParentSN int64  `json:"parentSN"`
	Parent string `gorm:"-" json:"parent"` // 父评论sn(空则为一级评论,否则为二级评论)

	PlateSN int64  `json:"plateSN"`
	Plate string `gorm:"-" json:"plate"` // 文章所属版块

	CreatedAt time.Time  `json:"createdAt"` // 创建时间
	UpdatedAt time.Time  `json:"updatedAt"` // 更新时间
	DeletedAt *time.Time `json:"deletedAt"` // 删除时间

	VoteUp       int64 `json:"voteUp"`       // 赞同数
	VoteDown     int64 `json:"voteDown"`     // 反对数
	RepliedTotal int64 `json:"repliedTotal"` // 被回复数

	Status       int64 `json:"status"`       // 状态(正常显示1,用户主动假删除2)
	ReviewStatus int64 `json:"reviewStatus"` // 审核状态(未审核1,通过2,审核不通过假删除3)
}

Plate string `gorm:"-" json:"plate"` // 文章所属版块

字段需要一致(大小写无所谓),否则上面的方法转不出来

到此这篇关于“golang mapstructure 转出为空的问题”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang 中 map 转 struct
Golang库 - viper读取配置文件
golang中遇到的问题
连nil切片和空切片一不一样都不清楚?那BAT面试官只好让你回去等通知了
golang json[]
一看就懂系列之Golang的Map如何做到最省空间?
Golang return 函数返回值的问题
golang在alpine中的坑
golang map 获取某个值
golang interface{} 转[]string

[关闭]
~ ~