[英]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&...¶mN=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.