个人第一个go样例,gin+gorm

最近从java转go了

自己没事手写个样例

1.注意事项

1.安装go  goland  git
2.下载以下依赖
go get -u github.com/jinzhu/gorm
go get -u github.com/gin-gonic/gin
3.如果下载失败
访问http://goproxy.io
设置代理下载依赖即可

2.main.go

package main

// only need mysql OR sqlite 
// both are included here for reference
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var db *gorm.DB
var err error

type Person struct {
	ID uint `json:"id" gorm:"primary_key"`
	FirstName string `json:"firstname"`
	LastName string `json:"lastname"`
	City string `json:"city"`
}

func main() {

	// NOTE: See we’re using = to assign the global var
	// instead of := which would assign it only in this function
	//db, err = gorm.Open("sqlite3", "./gorm.db")
	//db, err := gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	//
	//if err != nil {
	//	fmt.Println(err)
	//	panic(err)
	//}
	//defer db.Close()
	db :=Dbinit()

	db.AutoMigrate(&Person{})
	if !db.HasTable(&Person{}) {
		if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&Person{}).Error; err != nil {
			panic(err)
		}
	}
	r := gin.Default()
	//localhost:8080/people
	r.GET("/people/", GetPeople)
	//localhost:8080/people/1
	r.GET("/people/:id", GetPerson)
	//localhost:8080/people {"id":4,"firstname":"Elvis","lastname":"Presley","city":"beijing"}
	r.POST("/people", CreatePerson)
	//localhost:8080/people {"id":4,"firstname":"Elvis","lastname":"Presley","city":"beijing"}
	r.PUT("/people/:id", UpdatePerson)
	//localhost:8080/people/1
	r.DELETE("/people/:id", DeletePerson)

	r.Run(":8080")
}

func DeletePerson(c *gin.Context) {
	id := c.Params.ByName("id")
	var person Person
	db = Dbinit()
	d := db.Where("id = ?", id).Delete(&person)
	fmt.Println(d)
	c.JSON(200, gin.H{"id #" + id: "deleted"})
}

func UpdatePerson(c *gin.Context) {

	var person Person
	id := c.Params.ByName("id")
	db = Dbinit()
	if err := db.Where("id = ?", id).First(&person).Error; err != nil {
		c.AbortWithStatus(404)
		fmt.Println(err)
	}
	c.BindJSON(&person)

	db.Save(&person)
	c.JSON(200, person)

}

func CreatePerson(c *gin.Context) {
	var person Person
	c.BindJSON(&person)
	db = Dbinit()
	db.Create(&person)
	c.JSON(200, person)
}

func GetPerson(c *gin.Context) {
	id := c.Params.ByName("id")
	var person Person
	db = Dbinit()
	if err := db.Where("id = ?", id).First(&person).Error; err != nil {
		c.AbortWithStatus(404)
		fmt.Println(err)
	} else {
		c.JSON(200, person)
	}
}

func GetPeople(c *gin.Context) {
	var people []Person
	db = Dbinit()
	if err := db.Find(&people).Error; err != nil {
		c.AbortWithStatus(404)
		fmt.Println(err)
	} else {
		c.JSON(200, people)
	}
}

func Dbinit() *gorm.DB {
	db := NewConn()
	//SetMaxOpenConns用于设置最大打开的连接数
	//SetMaxIdleConns用于设置闲置的连接数
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	// 启用Logger,显示详细日志
	db.LogMode(true)

	// 自动迁移模式
	//db.AutoMigrate(&Model.UserModel{},
	//	&Model.UserDetailModel{},
	//	&Model.UserAuthsModel{},
	//)
	return db
}

func NewConn() *gorm.DB {
	db, err := gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic("连接数据库失败:" + err.Error())
	}
	return db
}

欢迎大家积极交流,我也不太懂go

你可能感兴趣的:(go,gin,gorm,go)