亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何向數據庫中插入多個值

如何向數據庫中插入多個值

Go
白衣非少年 2023-06-12 16:50:26
在我的 Go 應用程序中,我有這樣的路線:router.HandleFunc("/api/users_groups_relationship/{user_id:[0-9]+}", controllers.CreateUsersGroupsRelationship).Methods("POST")我發出POST請求。在該請求的正文中,我發送了如下所示的 JSON:{     "groups": [1, 2, 3]      }如您所見,groups鍵具有 id 數組作為值。用戶可以在多個組中。我正在嘗試將多個值插入到 PostgreSQL 數據庫中。如何獲取請求正文中特定鍵的值?還有其他最好的方法可以通過 Go 在數據庫中插入多個值嗎?我的代碼:var CreateUsersGroupsRelationship  = func(responseWriter http.ResponseWriter, request *http.Request) {    vars := mux.Vars(request)    userID := vars["user_id"]    fmt.Println(userID)    var groups []int    groups = request.Body("groups") // ???    for i := 1; i < len(groups); i++ {        fmt.Println(groups[i])        _, _ := database.DBSQL.Exec("INSERT INTO users_groups (user_id, group_id) VALUES ($1, $2);", userID, groups[i])    }    utils.ResponseWithSuccess(responseWriter, http.StatusOK, "All new records successfully created.")}
查看完整描述

1 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

您可以為 Request 對象定義一個結構,然后將 JSON 解組到其中。


package main


import (

    "fmt"

    "github.com/gorilla/mux"

    "net/http"

    "encoding/json"

)


//Request is our request body.

type Request struct {

    Groups []int `json:"groups"`

}


//JsonTest1 is the http handler.

func JsonTest1(w http.ResponseWriter, r *http.Request) {

    req := new(Request)

    //decode request to struct.

    if err := json.NewDecoder(r.Body).Decode(&req); err != nil{

        w.WriteHeader(400) //bad request

    }


    w.WriteHeader(200)

    b, _ := json.Marshal(req)

    w.Write(b)

    w.Header().Set("Content-Type", "application/json; charset=utf-8")

}


func main(){

    fmt.Printf("starting backend server\n")


    root := mux.NewRouter()

    root.HandleFunc("/foo", JsonTest1)


    webServer := &http.Server{Addr: ":4000", Handler: root}


    webServer.ListenAndServe()

}

如果您的主體非常通用,您也可以解組為 map[string]interface{}。


試試


curl -XPOST -d '{"groups": [1]}' http://localhost:4000/foo


查看完整回答
反對 回復 2023-06-12
  • 1 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號