我想验证来自golang前端的后端时区 [英] I want to validate timezone at the backend which is coming from the frontend in golang
问题描述
前端在注册期间发送时区以及其他用户详细信息.我需要在时区放置一个验证器以进行api测试.时区中的数据格式为:
The front-end is sending timezones along with other user details during sign up. I need to put a validator on timezone for api testing. The data in the timezone is of the format:
(GMT-10:00) Hawaii
(GMT-08:00) Pacific Time (US & Canada)
我所做的是在数组中定义所有时区,然后搜索接收到的时区.如果存在,则返回err.我的功能是:
What I did is define all the timezones in an array and then search for the received timezone. If it exists then ok else return err. My function is:
func timeZoneValidator(field validator.FieldLevel) bool {
if field.Field().Kind() != reflect.String {
return false
}
timeZoneField := field.Field().String()
for i:= range timeZones {
if timeZones[i] == timeZoneField {
// Found!
return true
}
}
return false
}
但是我想使用一个库或可以为我完成此任务的东西.如果有,请告知.
But I want to use a library or something that does this task for me. If you got any, please advise.
推荐答案
您也许可以使用 time.LoadLocation
.
You might be able to use time.LoadLocation
.
func LoadLocation(name string) (*Location, error)
您可以传入诸如"America/New_York"之类的字符串,并且错误返回信息会告诉您它是否有效.
You can pass in a string such as "America/New_York" and the error return should tell you if it's valid.
请注意,格式将与您当前使用的格式不同.查看 https://www.iana.org/time-zones
Note the format will be different from what you currently have. Check out https://www.iana.org/time-zones
这篇关于我想验证来自golang前端的后端时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!