繁体   English   中英

golang 结构体指针的使用方法

[英]how to use struct pointers in golang

我正在尝试用 gin post 做一个简单的 golang 并获取请求,除了应该在 struct 变量中的值是空的部分之外,其他一切都很好我的代码(主要)

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
}

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

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

例如:

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

需要使用大写字母,因为如果您不使用它,您只能在同一个 package 中看到。

大写字母 = 查看所有 package

普通字母 = 仅在相同的 package 中看到(例如:controller 仅在此处)

使用结构

如果字段或方法名称以大写字母开头,则该成员将被导出并且可以在 package 之外访问。

如果字段或方法以小写字母开头,则该成员未导出,并且在 package 之外无法访问。

注意:为了在 golang json package 中执行 Marshalling Un-marshalling 等操作,您需要字段名称应以大写字母开头。 因为它内部使用反射来处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM