如何向数据库中插入多个值

在我的 Go 应用程序中,我有这样的路线

router.HandleFunc("/api/users_groups_relationship/{user_id:[0-9]+}", controllers.CreateUsersGroupsRelationship).Methods("POST")

我发出POST请求。在该请求的正文中,我发送了如下所示的 JSON:

{
    "groups": [1, 2, 3] 
    }

如您所见,groups键具有 id 数组作为值。用户可以在多个组中。我正在尝试将多个值插入到 PostgreSQL 数据库中。

  1. 如何获取请求正文中特定键的值?

  2. 还有其他最好的方法可以通过 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.")

}


白衣非少年
浏览 145回答 1
1回答

喵喔喔

您可以为 Request 对象定义一个结构,然后将 JSON 解组到其中。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "github.com/gorilla/mux"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "encoding/json")//Request is our request body.type Request struct {&nbsp; &nbsp; Groups []int `json:"groups"`}//JsonTest1 is the http handler.func JsonTest1(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; req := new(Request)&nbsp; &nbsp; //decode request to struct.&nbsp; &nbsp; if err := json.NewDecoder(r.Body).Decode(&req); err != nil{&nbsp; &nbsp; &nbsp; &nbsp; w.WriteHeader(400) //bad request&nbsp; &nbsp; }&nbsp; &nbsp; w.WriteHeader(200)&nbsp; &nbsp; b, _ := json.Marshal(req)&nbsp; &nbsp; w.Write(b)&nbsp; &nbsp; w.Header().Set("Content-Type", "application/json; charset=utf-8")}func main(){&nbsp; &nbsp; fmt.Printf("starting backend server\n")&nbsp; &nbsp; root := mux.NewRouter()&nbsp; &nbsp; root.HandleFunc("/foo", JsonTest1)&nbsp; &nbsp; webServer := &http.Server{Addr: ":4000", Handler: root}&nbsp; &nbsp; webServer.ListenAndServe()}如果您的主体非常通用,您也可以解组为 map[string]interface{}。试试curl -XPOST -d '{"groups": [1]}' http://localhost:4000/foo
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go