[英]Is there a way to reuse a function for multiple structs in golang?
I'm writing a backend for a project, the backend receives the user data through a POST request encoded in the request body as json.我正在为一个项目编写后端,后端通过在请求正文中编码为 json 的 POST 请求接收用户数据。
I have two structures:我有两种结构:
struct to store user data during new account creation:在新帐户创建期间存储用户数据的结构:
type User struct {
Guid string ``
Name string `json:"Name"`
Pass string `json:"Pass"`
Username string `json:"Username"`
Email string `json:"Email"`
Phone string `json:"Phone"`
Country string `json:"Country"`
}
struct to store signin data用于存储登录数据的结构
type Signin struct {
Username string `json:"Username"`
Pass string `json:"Pass"`
}
and a json decoder function (to decode the data from the request body):和一个 json 解码器函数(用于解码来自请求正文的数据):
func extractAndAssignInfo(req *http.Request, dataStruct interface{}) interface{}{
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&dataStruct)
if err != nil {
log.Fatal(err)
}
return reflect.ValueOf(dataStruct).Interface()
}
Is there a way to have the extractAndAssignInfo()
function to return the struct?有没有办法让extractAndAssignInfo()
函数返回结构?
Since the Guid is calculated using a different function, when I try to do由于 Guid 是使用不同的函数计算的,当我尝试做
userdata := ExtractAndAssignInfo(req, User{})
The return value of the function gives a type of map[string]interface {}
, if I change the return type to a struct then it won't be a "general purpose" function that can decode and return the required struct.该函数的返回值给出了一种类型的map[string]interface {}
,如果我将返回类型更改为结构,那么它将不是一个可以解码并返回所需结构的“通用”函数。
I'm not sure if this is the best approach to solving it.我不确定这是否是解决它的最佳方法。 I would also appreciate any other way I can reuse that same function while returning a struct.我也很感激我可以在返回结构时重用相同函数的任何其他方式。
Use this function:使用这个功能:
func extractAndAssignInfo(req *http.Request, v interface{}) {
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(v)
if err != nil {
log.Fatal(err)
}
}
Call it like this to decode the request to a User
:像这样调用它以解码对User
的请求:
var userData User
extractAndAssignInfo(req, &userData)
and like this to decode to a Signin
:并像这样解码为Signin
:
var signin Signin
extractAndAssignInfo(req, &signin)
Side node: It's not a good idea to exit the process on bad request data.侧节点:对于错误的请求数据退出进程不是一个好主意。 Consider returning an error extractAndAssignInfo
instead of calling log.Fatal
.考虑返回一个错误extractAndAssignInfo
而不是调用log.Fatal
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.