package main
import (
"github.com/gin-gonic/gin"
"html/template"
"i9iweb/model"
"i9iweb/routers"
)
func main() {
r := gin.Default()
//funcMap必须在模板之前
r.SetFuncMap(template.FuncMap{
"formatDate": model.Format,
})
//设置静态文件路径
r.Static("/static", "./static")
//加载模板页面
r.LoadHTMLGlob("templates/**/**")
//使用中间件,可以有多个中间件
r.Use(corsMiddleware())
//初始化路由
routers.InitRouter(r)
//启动监听端口
err := r.Run("0.0.0.0:9000")
if err != nil {
return
}
}
// corsMiddleware 返回CORS中间件处理函数
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 允许所有的跨域请求
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
c.Header("Access-Control-Max-Age", "86400") // 预检请求缓存时间,单位为秒
// 处理预检请求
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
return
}
// 继续处理其他请求
c.Next()
}
}
package routers
import (
"github.com/gin-gonic/gin"
"i9iweb/web"
)
func InitRouter(r *gin.Engine) {
InitIndexRouter(r)
InitNewsRouter(r)
}
func InitIndexRouter(r *gin.Engine) {
router := r.Group("/")
{
indexWeb := web.IndexWeb{}
router.GET("/", indexWeb.Index)
router.POST("/upload", indexWeb.Upload)
}
}
func InitNewsRouter(r *gin.Engine) {
router := r.Group("/news")
{
newsWeb := web.NewsWeb{}
router.GET("/", newsWeb.News)
router.POST("/", newsWeb.AddNews)
router.PATCH("/", newsWeb.UpdateNews)
router.DELETE("/:id", newsWeb.DeleteNews)
router.GET("/:id", newsWeb.GetById)
}
}
package web
import (
"github.com/gin-gonic/gin"
"io/fs"
"net/http"
"os"
"path"
"strconv"
"time"
)
type IndexWeb struct {
}
func (web IndexWeb) Index(c *gin.Context) {
//这个位置不能写成 /index/index.html 必须 index/index.html不然返回是空
c.HTML(http.StatusOK, "index/index.html", gin.H{
"title": "首页",
"content": "首页内容",
"date": time.Now(),
})
}
func (web IndexWeb) Upload(c *gin.Context) {
name := c.PostForm("name")
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": -1,
"msg": "文件上传失败",
})
return
}
dir := path.Join("./static/upload", time.Now().Format("20060102"))
err1 := os.MkdirAll(dir, fs.ModeDir)
if err1 != nil {
c.JSON(http.StatusOK, gin.H{
"code": -1,
"msg": "创建目录失败",
})
return
}
dst := path.Join(dir, strconv.FormatInt(time.Now().Unix(), 10)+path.Ext(file.Filename))
err2 := c.SaveUploadedFile(file, dst)
if err2 != nil {
c.JSON(http.StatusOK, gin.H{
"code": -1,
"msg": "文件保存失败",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "文件上传成功",
"path": dst,
"name": name,
})
}
package web
import (
"fmt"
"github.com/gin-gonic/gin"
"i9iweb/dao"
"i9iweb/model"
"net/http"
"strconv"
)
type NewsWeb struct {
}
func (web NewsWeb) News(c *gin.Context) {
var newsParam model.NewsQuery
err := c.ShouldBind(&newsParam)
if err != nil {
return
}
fmt.Println("pageSize:", newsParam.PageSize, "page:", newsParam.Page)
if newsParam.PageSize < 1 || newsParam.PageSize > 100 {
newsParam.PageSize = 10
}
if newsParam.Page < 1 {
newsParam.Page = 1
}
newsDao := dao.NewsDao{}
news := newsDao.List(newsParam)
c.JSON(http.StatusOK, model.OK(news))
}
func (web NewsWeb) AddNews(c *gin.Context) {
news := &model.NewsModel{}
err := c.ShouldBind(news)
if err != nil {
c.JSON(http.StatusOK, model.Error("参数错误"))
return
}
newsDao := dao.NewsDao{}
news = newsDao.Add(news)
c.JSON(http.StatusOK, model.OK(news))
}
func (web NewsWeb) UpdateNews(c *gin.Context) {
news := &model.NewsModel{}
err := c.ShouldBind(news)
if err != nil {
c.JSON(http.StatusOK, model.Error("参数错误"))
return
}
newsDao := dao.NewsDao{}
news = newsDao.Update(news)
c.JSON(http.StatusOK, model.OK(news))
}
func (web NewsWeb) DeleteNews(c *gin.Context) {
idStr := c.Param("id")
id, _ := strconv.ParseInt(idStr, 10, 64)
//id := c.GetInt64("id")
if id <= 0 {
c.JSON(http.StatusOK, model.Error("参数异常"))
return
}
newsDao := dao.NewsDao{}
newsDao.Delete(uint(id))
c.JSON(http.StatusOK, model.OK())
}
func (web NewsWeb) GetById(c *gin.Context) {
idStr := c.Param("id")
id, _ := strconv.ParseInt(idStr, 10, 64)
if id <= 0 {
c.JSON(http.StatusOK, model.Error("参数异常"))
return
}
newsDao := dao.NewsDao{}
news := newsDao.GetById(uint(id))
c.JSON(http.StatusOK, model.OK(news))
}
package dao
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"i9iweb/model"
"time"
)
var DB *gorm.DB
var err error
func init() {
dsn := "root:mysql@tcp(localhost:3306)/db001?charset=utf8mb4&parseTime=True&loc=Local"
DB, err = gorm.Open(mysql.New(mysql.Config{
DSN: dsn, // DSN data source name
DefaultStringSize: 256, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
}), &gorm.Config{})
DB.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&model.NewsModel{})
if err != nil {
fmt.Println(err)
}
sqlDB, err2 := DB.DB()
if err2 != nil {
fmt.Println(err2)
}
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Hour)
}
package dao
import (
"fmt"
"i9iweb/model"
"strings"
)
type NewsDao struct {
}
func (dao NewsDao) TableName() string {
return "news"
}
func (dao NewsDao) List(param model.NewsQuery) []model.NewsModel {
var news []model.NewsModel
query := DB.Model(&model.NewsModel{})
//query = query.Offset((param.Page - 1) * param.PageSize).Limit(param.PageSize)
if strings.Trim(param.StartCreateAt, " ") != "" {
query = query.Where("created_at >= ?", param.StartCreateAt)
}
if strings.Trim(param.EndCreateAt, " ") != "" {
query = query.Where("created_at <= ?", param.EndCreateAt)
}
if strings.Trim(param.Title, " ") != "" {
query = query.Where("title like ?", "%"+param.Title+"%")
}
if strings.Trim(param.Author, " ") != "" {
query = query.Where("author like ?", "%"+param.Author+"%")
}
if strings.Trim(param.Content, " ") != "" {
query = query.Where("content like ?", "%"+param.Content+"%")
}
if param.ID > 0 {
query = query.Where("id=?", param.ID)
}
if err := query.Offset(param.Offset()).Limit(param.PageSize).Order("id desc").Find(&news); err != nil {
fmt.Println(err)
return news
}
return news
//DB.Find(&news)
//for _, item := range news {
// fmt.Println(item)
//}
//分页查询NewsModel
//query, err := db.Query("select * from news")
//if err != nil {
// return
//}
//for rows:=query;rows!=nil {
// fmt.Println(rows),
//}
}
func (dao NewsDao) Add(news *model.NewsModel) *model.NewsModel {
//news.AddTime = time.Now().Format("2016-01-02 15:03:04")
DB.Create(news)
return news
}
func (dao NewsDao) Delete(id uint) bool {
DB.Delete(&model.NewsModel{}, id)
return true
}
func (dao NewsDao) Update(news *model.NewsModel) *model.NewsModel {
var old = &model.NewsModel{}
old.ID = news.ID
DB.Find(old)
old.Title = news.Title
old.Content = news.Content
old.Author = news.Author
DB.Save(old)
//DB.Model(&news).Update("title", news.Title)
//DB.Model(&news).Update("author", news.Author)
return old
}
func (dao NewsDao) GetById(id uint) model.NewsModel {
var one = model.NewsModel{}
one.ID = id
//DB.Find(&one).Where("id=?", id)
DB.Find(&one)
return one
}
{{ define "index/index.html" }}
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.title}}</title>
</head>
<body>
<h1>首页--{{.title}}</h1>
{{ .content}}
{{ .date|formatDate}}
<form action="/upload" method="post" enctype="multipart/form-data">
名称:<input type="text" name="name"><br>
文件:<input type="file" name="file"><br>
<input type="submit" value="提交"> <br>
</form>
<form action="/news/add" method="post">
标题 <input type="text" name="title"><br>
内容 <input type="text" name="content"><br>
作者 <input type="text" name="author"><br>
<input type="submit" value="提交"> <br>
</form>
</body>
</html>
{{end}}
package model
import "time"
type QueryModel struct {
Page int `json:"page" form:"page" `
PageSize int `json:"pageSize" form:"pageSize" `
StartCreateAt string `json:"startAddTime" form:"startAddTime" `
EndCreateAt string `json:"endAddTime" form:"endAddTime" `
}
func (qm QueryModel) Offset() int {
return (qm.Page - 1) * qm.PageSize
}
type RT struct {
Code int `json:"code" form:"code" xml:"code"`
Msg string `json:"msg" form:"msg" xml:"msg"`
Data interface{} `json:"data" form:"data" xml:"data"`
}
func OK(data ...interface{}) RT {
r := RT{}
r.Code = 0
r.Msg = "请求成功"
r.Data = data
return r
}
func Error(msg string) RT {
r := RT{}
r.Code = 0
r.Msg = "请求失败" + msg
return r
}
func Format(t time.Time) string {
//year, month, day := t.Date()
//return fmt.Sprintf("%v-%v-%v", year, month, day)
return t.Format("2006-01-02 15:04:05")
}
package model
import (
"gorm.io/gorm"
)
type NewsModel struct {
gorm.Model
Title string `json:"title" form:"title" xml:"title" gorm:"title"`
Content string `json:"content" form:"content" xml:"content" gorm:"content"`
Author string `json:"author" form:"author" xml:"author" gorm:"author"`
}
func (model NewsModel) TableName() string {
return "t_news"
}
type NewsQuery struct {
NewsModel
QueryModel
}