golang中如何使用结构体指针

阿纳楚南·迈克尔

我正在尝试用 gin post 和 get request 做一个简单的 golang,其他一切都很好,除了应该在结构变量中的值是空的部分之外,如果我没有很好地解释,这个例子就在下面我的代码(主要)

package main

import (
    //"fmt"
    "github.com/cosimmichael/assessment/app/db_client"
    "github.com/cosimmichael/assessment/app/controllers"
    "github.com/gin-gonic/gin"
    // you need to import go mod  init for this parkage to work
    // "github.com/cosimmichael/assessment/app/strutil"
    // "github.com/cosimmichael/assessment/app/routers"
    // "net/http"
)

func main(){
    db_client.InitialiseDBConnection()

    r := gin.Default()

    r.POST("api/v1/products/create", controller.CreateProducts)
    r.GET("api/v1/products/{product_id}/show", controller.GetPosts)

    if err := r.Run(":3000"); err != nil {
        panic(err.Error())
    }
    // router.HandleRoutes()
    // fmt.Println("Server Starting.. @ port :3000")
    // http.ListenAndServe(":3000", nil)
}

我的代码(控制器)

package controller

import (
    "net/http"
    "github.com/gin-gonic/gin"
    "github.com/cosimmichael/assessment/app/db_client"
    // "fmt"
)

type Post struct {
    id int64            `json: "id"`
    title *string       `json: "title"`
    description *string     `json: "description"`
}

func CreateProducts(c *gin.Context) {
    var reqBody Post
    if err := c.ShouldBindJSON(&reqBody); err != nil {
        c.JSON(http.StatusUnprocessableEntity, gin.H{
            "error": true,
            "message": "Invalid request body",
        })
        return
    }

    res, err := db_client.DBClient.Exec("INSERT INTO products (title, description) VALUES (?, ?);", 
        reqBody.title,//"testing",
        reqBody.description,//"Just testing something",
    )
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": true,
            "message": "Invalid request body2",
        })
        return
    }

    id, err := res.LastInsertId()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": true,
            "message": "Invalid request body3",
        })
        return
    }

    c.JSON(http.StatusCreated, gin.H{
        "error": false,
        "id": id,
    })
}

func GetPosts(c *gin.Context){
    var posts []Post

    rows, err := db_client.DBClient.Query("SELECT id, title, description FROM products;")
    if err != nil {
        c.JSON(http.StatusUnprocessableEntity, gin.H{
            "error": true,
            "message": "Invalid request body",
        })
        return
    }

    for rows.Next(){
        var singlePost Post
        if err := rows.Scan(&singlePost.id, &singlePost.title, &singlePost.description); err != nil {
            c.JSON(http.StatusUnprocessableEntity, gin.H{
                "error": true,
                "message": "Invalid request body",
            })
            return
        }
        posts = append(posts, singlePost)
    }

    c.JSON(http.StatusOK, rows)
}


我的代码 db_client

package db_client

import (
    "database/sql"
    //"time"
    _ "github.com/go-sql-driver/mysql"
)

var DBClient *sql.DB

func InitialiseDBConnection(){
    //[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]
    db, err := sql.Open("mysql","root:2580@tcp(localhost:3306)/grabit?parseTime=true")
    if err != nil {
        panic(err.Error())
    }
    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

    DBClient = db
}

现在,当我使用邮递员插入新行时,它会插入一个只有 id、没有标题或描述的空行,当我尝试获取时,我得到一个空数组,请问有什么问题,我是 golang 新手

灰色

您需要将 struct 字段中值的第一个字符大写。

例如:

type Book struct {
  ID     uint   `json:"id" gorm:"primary_key"`
  Title  string `json:"title"`
  Author string `json:"author"`
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何使用结构体指针转换[] byte?

来自分类Dev

使用结构体中的指针访问数组

来自分类Dev

使用Golang中的reflect将通过interface {}传递的结构体的指针设置为nil?

来自分类Dev

结构体中的指针值

来自分类Dev

如何使用接口实现的方法更改结构体中变量的指针

来自分类Dev

如何正确使用结构体中的const字符串指针?

来自分类Dev

通过指针访问结构体中的指针

来自分类Dev

指向结构体中的指针的指针

来自分类Dev

如何使用指针访问结构体数组的位置

来自分类Dev

如何从Golang中的切片获取结构指针

来自分类Dev

用于使用结构体指针循环结构体成员

来自分类Dev

使用反射在Golang中打印结构指针字段类型

来自分类Dev

使用Golang中的结构体将方法转换为函数

来自分类Dev

如何使用双指针正确引用结构中的指针

来自分类Dev

当您有一个指向结构体指针的指针时,如何使用realloc?

来自分类Dev

如何使用函数访问结构中的结构指针?

来自分类Dev

在结构体中设置指针的值

来自分类Dev

指针和结构体中的char

来自分类Dev

指向结构体中数组的指针

来自分类Dev

结构体中的指针奇怪的结果

来自分类Dev

从结构体中的指针获取数组

来自分类Dev

防止结构体中的char指针溢出

来自分类Dev

C使用指向结构体的指针

来自分类Dev

如何在Go中获取结构体中字段的真正指针?

来自分类Dev

引用结构体中的指针时是否可以使用“ cin”?

来自分类Dev

如何正确使用结构指针?

来自分类Dev

在定义结构之前如何使用结构指针?

来自分类Dev

如何使用位于结构中的函数指针运行函数?(C)

来自分类Dev

如何使用Memcpy初始化结构体中的数组

Related 相关文章

热门标签

归档