我有一個典型的函數,它從前端接收一個 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"}
抽象 PSQL 寫查詢
慕碼人8056858
2023-03-29 15:42:41