我有一个典型的函数,它接收来自前端的post请求,并将数据解码为结构,以便将其放入psql数据库。你可以看到下面的代码。我的问题是我希望能够抽象这个函数,这样我就可以给它任何数量的任何类型的变量,这样对于每个请求我就不必有单独的写处理程序。
这看起来很难,因为我必须以某种方式通过抽象
var profitReq profitReq
为任何建筑工作。如果golang有某种eval string方法,我会知道如何做到这一点,但是如果我错了,有人会纠正我,但我不这么认为。
我需要改变的另一个地方是在QueryRow中-我必须能够在一个变量的数量可变的情况下传递它。我可以很容易地构造这个字符串,但是我不知道如何将变量附加到那个QueryRow。例如,如果我将所有变量附加到一个数组中,我就不能将该数组传递到QueryRow中,因为它不是这样构造的。再说一次,这里的一些eval语句会有所帮助。
感谢任何能帮忙的人!
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"
}