我有一个典型的函数,它从前端接收一个 post 请求并将数据解码为一个结构,以便将其放入 psql 数据库中。你可以看到下面的代码。我的问题是我希望能够抽象这个函数,这样我就可以给它任何数量的任何类型的变量,这样对于每个请求我都不必有一个单独的写处理程序。
这看起来很难,因为我将不得不以某种方式传递一种抽象的方式来var profitReq profitReq为任何结构工作。如果 golang 有某种 eval string 方法,我会知道该怎么做,但如果我错了,有人会纠正我,但我认为它不会。
我需要更改的另一个地方是 QueryRow - 我必须能够将它传递给可变数量的变量。我可以很容易地构造字符串,但我不确定如何将变量附加到该 QueryRow。例如,如果我将所有变量附加到一个数组,我不能将该数组传递到 QueryRow,因为它不是这样构造的。同样,这里某种 eval 语句会有所帮助。
我是golang的新手,但是我看到了很多与接口相关的很酷的东西,我承认我不是很了解。有没有办法在这里使用一个有帮助的界面?
感谢任何能提供帮助的人!
func Write_profit_table(profitWriteChannel chan string, profitType string, req *http.Request) {
var profitReq profitReq;
err := json.NewDecoder(req.Body).Decode(&profitReq);
if err!=nil{
log.Panic(err)
}
NotInDB, _ := Search_userinfo_table(profitReq.Email)
if NotInDB == false {
var lastInsertId int
err2 := db.QueryRow("INSERT INTO profit(email, type, dateArray, amount, interest, compounded, recurring, name, description, profitFrom)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) returning uid;",
profitReq.Email, profitReq.Type, pq.Array(profitReq.DateArray), profitReq.Profit, profitReq.Interest,
profitReq.Compounded, profitReq.Recurring, profitReq.Name, profitReq.Description, profitReq.ProfitFrom).Scan(&lastInsertId);
if err2!=nil{
log.Panic(err2)
}
}
profitWriteChannel<-"finished writing to profit"
}
动漫人物
相关分类