Wails中Go结构或方法无法映射到前端
Reverse Lv4

概述

最近发现一个奇怪的问题,我执行wails dev时突然发现我在app.go中暴露给前端的函数居然没能自动绑定到前端的wailsjs/go/apps/xxx下。

经过一段时间排查发现是 go 语言导出函数的返回值带有复杂类型,就是time.Time这个类型导致的,原因很简单。

执行命令尝试手动让他去绑定:

1
wails generate module

然后出现了错误

1
2
3
4
5
6
7
8
╭─hyhacct@hyhacctdeMacBook-Air ~/workspace/PeachDRAC/PeachDRAC ‹main●›
╰─$ wails generate module 1 ↵
2025/04/24 13:24:14 KnownStructs: model.TablePass model.WailsCommunicate
Not found: time.Time
KnownStructs: model.TablePass model.WailsCommunicate
Not found: time.Time

♥ If Wails is useful to you or your company, please consider sponsoring the project:

这里就是在说 wails 其实并不支持time.Time这个类型,但是恰好我暴露的函数中,有一个返回值是结构体,结构体里面有个值类型就是time.Time

然后这个问题就顺其而然的产生了…

解决办法

直接在对应的结构体这个类型下,给他添加一个映射: ts_type:"string"

意思就是告诉 Wails 将 time.Time 序列化为字符串,不将他作为一个特殊类型处理,其实就可以了。

具体示例:(在对应的特殊类型后面添加ts_type映射)

1
2
3
4
5
6
7
8
9
10
type TablePass struct {
ID int `gorm:"primary_key" json:"id"`
Username string `gorm:"not null" json:"username"`
Password string `gorm:"not null" json:"password"`
Port string `gorm:"not null" json:"port"`
Status bool `gorm:"not null" json:"status"` // 是否启用
Priority int `gorm:"not null" json:"priority"` // 优先级,数字越大越高
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" ts_type:"string"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" ts_type:"string"`
}

然后执行自动绑定,发现没有任何错误,OK,问题顺利解决。

1
2
3
4
5
6
╭─hyhacct@hyhacctdeMacBook-Air ~/workspace/PeachDRAC/PeachDRAC ‹main●›
╰─$ wails generate module
♥ If Wails is useful to you or your company, please consider sponsoring the project:
https://github.com/sponsors/leaanthony
╭─hyhacct@hyhacctdeMacBook-Air ~/workspace/PeachDRAC/PeachDRAC ‹main●›
╰─$