golang gin框架 CURD

1、代码分层

        1.1 gin 启动http 服务

                router := gin.Default()
                router.GET("/index",function(c *gin.Context ){})

                router.Run() // 初学者会忘 不写 无法看到http效果

                

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func addBook(c *gin.Context)  {
	if c.Request.Method == "POST" {
		title := c.DefaultPostForm("title","无名")
		price := c.DefaultPostForm("price","0.1")
		price64,err := strconv.ParseFloat(price,64)
		if err != nil {
			c.JSON(http.StatusPartialContent,gin.H{
				"msg":"价格参数错误",
			})
		}
		err = insertBook(title,price64)
		if err != nil {
			//添加成功 跳转到 列表页
			panic(err)
		}
		c.Redirect(http.StatusMovedPermanently,"/book/list")
		return
	}
	c.HTML(http.StatusOK,"book/add_book.html",nil)
}
func deleteBook(c *gin.Context)  {
	id := c.Query("id")
	fmt.Println(id)
	id64,_ := strconv.ParseInt(id,10,10)
	fmt.Println(id64)
	deleteBook2(id64)
	c.Redirect(http.StatusMovedPermanently,"/book/list")
}
func bookList(c *gin.Context)  {
	allBook,err := QueryAllBook()
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":1,
			"msg":err,
		})
		return
	}
	//c.JSON(http.StatusOK, gin.H{
	//	"code" :0,
	//	"msg" : "success",
	//	"data" :allBook,
	//})
	//return
	c.HTML(http.StatusOK,"book/book_list.html",gin.H{
		"data":allBook,
	})
}
func main()  {
	err:= initDB()
	if err != nil {
		panic(err)
	}
	//建立一个http serve
	//路由 方法
	router := gin.Default()
	//加载html文件
	router.LoadHTMLGlob("templates/**/*")
	router.GET("/book/new",addBook)
	router.POST("/book/add",addBook)
	//router.DELETE("/book/delete",deleteBook)
	router.GET("/book/delete",deleteBook)
	router.GET("/book/list",bookList)
	router.Run(":9090")
}

        1.2 实例化db

                

package main

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var db *sqlx.DB

func initDB() (err error) {
	dsn := "root:123456@tcp(127.0.0.1:3306)/ginchat2023"
	db,err = sqlx.Connect("mysql",dsn)
	if err != nil {
		return err
	}
	db.SetMaxIdleConns(16)
	db.SetMaxOpenConns(100)
	return nil
}

        1.3 table 表的 mode 读写。

                

package main

import "fmt"

type Book struct {
	ID int `json:"id"`
	Title string `json:"title"`
	Price float64 `json:"price"`
}

func QueryAllBook() (allBook []*Book, err error) {
	sqlStr := "select * from book"
	err = db.Select(&allBook,sqlStr)
	if err != nil {
		fmt.Println("查询所有书本失败")
		return
	}
	return
}

func insertBook(title string, price float64)  (err error) {
	sql := "INSERT INTO book(title,price) values(?,?)"
	result,err := db.Exec(sql,title,price)
	if err != nil {
		fmt.Printf("inert into err: %s ",err)
		return err
	}
	_,err = result.LastInsertId()
	if err != nil {
		fmt.Printf("LastInsertId err: %s ",err)
		return err
	}
	return err
}

func deleteBook2(id int64)  {
	sql := "delete from book where id=?"
	fmt.Println(sql,id)
	_,err := db.Exec(sql,id)
	if err != nil {
		fmt.Printf("deleteBook err: %s ",err)
		return
	}
	return
}

        1.4 go 使用 template 语法 实现 前端 html 渲染

                router.LoadHTMLGlob("templates/**/*")

    

*** 注意接收的参数类型需要对应转换如:price64:= strconv.ParseFloat(price,64)

你可能感兴趣的:(golang,gin,开发语言,后端,云原生)