gluamapper 项目使用教程

gluamapper 项目使用教程

gluamappergluamapper: maps a GopherLua table to a Go struct项目地址:https://gitcode.com/gh_mirrors/gl/gluamapper

1. 项目的目录结构及介绍

gluamapper/
├── gluamapper.go
├── README.md
└── LICENSE
  • gluamapper.go: 项目的主要源文件,包含了将 GopherLua 表映射到 Go 结构体的功能。
  • README.md: 项目的说明文档,提供了项目的基本信息和使用方法。
  • LICENSE: 项目的许可证文件,本项目采用 MIT 许可证。

2. 项目的启动文件介绍

项目的启动文件是 gluamapper.go,该文件定义了 gluamapper 包,主要功能是将 GopherLua 表转换为 Go 结构体。以下是文件的主要内容:

package gluamapper

import (
	"github.com/yuin/gopher-lua"
	"github.com/mitchellh/mapstructure"
)

type Option struct {
	TagName string
	DecodeHook interface{}
}

func Map(L *lua.LState, table *lua.LTable, v interface{}, options ...Option) error {
	mapper := newMapper(options...)
	mp, err := mapper.mapToMap(table)
	if err != nil {
		return err
	}
	return mapper.decode(mp, v)
}

func newMapper(options ...Option) *mapper {
	m := &mapper{
		TagName: "gluamapper",
	}
	for _, option := range options {
		if option.TagName != "" {
			m.TagName = option.TagName
		}
		m.DecodeHook = option.DecodeHook
	}
	return m
}

type mapper struct {
	TagName string
	DecodeHook interface{}
}

func (m *mapper) mapToMap(table *lua.LTable) (map[string]interface{}, error) {
	mp := make(map[string]interface{})
	table.ForEach(func(k lua.LValue, v lua.LValue) {
		mp[k.String()] = v
	})
	return mp, nil
}

func (m *mapper) decode(input interface{}, output interface{}) error {
	config := &mapstructure.DecoderConfig{
		Metadata: nil,
		Result:   output,
		TagName:  m.TagName,
	}
	if m.DecodeHook != nil {
		config.DecodeHook = m.DecodeHook
	}
	decoder, err := mapstructure.NewDecoder(config)
	if err != nil {
		return err
	}
	return decoder.Decode(input)
}

3. 项目的配置文件介绍

项目没有专门的配置文件,所有的配置都是通过代码中的 Option 结构体进行设置的。以下是 Option 结构体的定义:

type Option struct {
	TagName string
	DecodeHook interface{}
}
  • TagName: 用于指定映射时使用的标签名称,默认为 "gluamapper"
  • DecodeHook: 用于在映射过程中进行自定义转换的钩子函数。

通过在调用 Map 函数时传入 Option 参数,可以自定义映射的行为。例如:

var person Person
options := gluamapper.Option{
	TagName: "json",
}
if err := gluamapper.Map(L, L.GetGlobal("person").(*lua.LTable), &person, options); err != nil {
	panic(err)
}

以上代码将使用 "json" 标签进行映射。

gluamappergluamapper: maps a GopherLua table to a Go struct项目地址:https://gitcode.com/gh_mirrors/gl/gluamapper

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汤璞亚Heath

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值