项目结构
–controller
-stories.go
–database
-connect.go
-main.go
项目源码
connect.go
package database
import ("database/sql"
_ "github.com/Go-SQL-Driver/MySQL"
)
func DBConn()(db *sql.DB) {
dbDriver := "mysql"
dbUser := "root"
dbPass := "123456"
dbName := "test"
db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
if err != nil {
panic(err.Error())
}
return db
}
main.go
package main
import (
"awesomeProject2/controller"
"github.com/gin-gonic/gin"
)
func setupRouter() *gin.Engine {
client :=gin.Default()
client.GET("/stories",controller.Show)
return client
}
func main() {
r :=setupRouter()
r.Run(":8080")
}
stories.go
package controller
import (
"awesomeProject2/database"
"github.com/gin-gonic/gin"
)
type Story struct {
Id int `json:"id"`
Title string `json:"title"`
Content string `json:"body"`
}
func Show(c * gin.Context) {
db:=database.DBConn()
rows,err:=db.Query("select * from person ")
if err !=nil {
c.JSON(500,gin.H{"message":err.Error(),
})
}
var listStories [] Story
for rows.Next() {
var id int
var title ,body string
story :=Story{}
err = rows.Scan(&id,&title,&body)
if err !=nil {
panic(err.Error())
}
story.Id=id
story.Title=title
story.Content=body
listStories=append(listStories,story)
}
c.JSON(200,listStories)
defer db.Close()
}
带有前段请求的增删改查(postman)
main.go:
package main
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/user", func(c *gin.Context) {
users, err := GetAll()
if err !=nil{
log.Fatal(err)
c.JSON(500,gin.H{
"result":"faile",
})
}
c.JSON(http.StatusOK,gin.H{
"result":users,
"count":len(users),
})
})
router.Run(":8080")
}
mysql.go:
package main
import (
"database/sql"
"log"
_ "github.com/Go-SQL-Driver/MySQL"
)
type User struct {
Id int `json:"id"`
Username string `json:"user_name"`
Password string `json:"pass_word"`
}
func DBConn()(db *sql.DB) {
dbDriver := "mysql"
dbUser := "root"
dbPass := "123456"
dbName := "test"
db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
if err != nil { panic(err.Error()) }
return db }
func GetAll() (users []User,err error) {
db:=DBConn()
if err!= nil{
log.Fatal(err.Error())
}
defer db.Close()
rows,err:=db.Query("select id,username,password from person")
if err != nil {
log.Fatal(err.Error())
}
for rows.Next() {
var user User
rows.Scan(&user.Id,&user.Username,&user.Password)
users = append(users, user)
}
defer rows.Close()
return
}
用postman请求: