package main
import (
"gindemo12/models"
"gindemo12/routers"
"html/template"
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
//自定义模板函数 注意要把这个函数放在加载模板前
r.SetFuncMap(template.FuncMap{
"UnixToTime": models.UnixToTime,
})
//加载模板 放在配置路由前面
r.LoadHTMLGlob("templates/**/*")
//配置静态web目录 第一个参数表示路由, 第二个参数表示映射的目录
r.Static("/static", "./static")
routers.AdminRoutersInit(r)
routers.ApiRoutersInit(r)
routers.DefaultRoutersInit(r)
r.Run(":80")
}
package admin
import (
"net/http"
"github.com/gin-gonic/gin"
)
type ArticleController struct {
BaseController
}
func (con ArticleController) Index(c *gin.Context) {
con.success(c)
}
func (con ArticleController) Add(c *gin.Context) {
c.String(http.StatusOK, "-add--文章-")
}
func (con ArticleController) Edit(c *gin.Context) {
c.String(http.StatusOK, "-Edit---文章---")
}
package admin
import "github.com/gin-gonic/gin"
type BaseController struct{}
func (con BaseController) success(c *gin.Context) {
c.String(200, "成功")
}
func (con BaseController) error(c *gin.Context) {
c.String(200, "失败")
}
package admin
import (
"fmt"
"github.com/gin-gonic/gin"
)
type IndexController struct {
}
func (con IndexController) Index(c *gin.Context) {
username, _ := c.Get("username")
fmt.Println(username)
//类型断言
v, ok := username.(string)
if ok {
c.String(200, "用户列表--"+v)
} else {
c.String(200, "用户列表--获取用户失败")
}
}
package admin
import (
"fmt"
"gindemo12/models"
"net/http"
"os"
"path"
"strconv"
"github.com/gin-gonic/gin"
)
type UserController struct {
BaseController
}
func (con UserController) Index(c *gin.Context) {
c.String(200, "用户列表--")
// con.success(c)
}
func (con UserController) Add(c *gin.Context) {
c.HTML(http.StatusOK, "admin/useradd.html", gin.H{})
}
/*
1、获取上传的文件
2、获取后缀名 判断类型是否正确 .jpg .png .gif .jpeg
3、创建图片保存目录 static/upload/20200623
4、生成文件名称和文件保存的目录
5、执行上传
*/
func (con UserController) DoUpload(c *gin.Context) {
username := c.PostForm("username")
// 1、获取上传的文件
file, err := c.FormFile("face")
if err == nil {
// 2、获取后缀名 判断类型是否正确 .jpg .png .gif .jpeg
extName := path.Ext(file.Filename)
allowExtMap := map[string]bool{
".jpg": true,
".png": true,
".gif": true,
".jpeg": true,
}
if _, ok := allowExtMap[extName]; !ok {
c.String(200, "上传的文件类型不合法")
return
}
// 3、创建图片保存目录 static/upload/20210624
day := models.GetDay()
dir := "./static/upload/" + day
err := os.MkdirAll(dir, 0666)
if err != nil {
fmt.Println(err)
c.String(200, "MkdirAll失败")
return
}
// 4、生成文件名称和文件保存的目录 111111111111.jpeg
fileName := strconv.FormatInt(models.GetUnix(), 10) + extName
// 5、执行上传
dst := path.Join(dir, fileName)
c.SaveUploadedFile(file, dst)
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"username": username,
})
}
package api
import "github.com/gin-gonic/gin"
type ApiController struct{}
func (con ApiController) Index(c *gin.Context) {
c.String(200, "我是一个api接口")
}
func (con ApiController) Userlist(c *gin.Context) {
c.String(200, "我是一个api接口-Userlist")
}
func (con ApiController) Plist(c *gin.Context) {
c.String(200, "我是一个api接口-Plist")
}
package itying
import (
"net/http"
"github.com/gin-gonic/gin"
)
type DefaultController struct{}
func (con DefaultController) Index(c *gin.Context) {
//设置cookie
//3600表示的是秒
c.SetCookie("username", "张三", 3600, "/", ".itying.com", false, true)
c.HTML(http.StatusOK, "default/index.html", gin.H{
"msg": "我是一个msg",
"t": 1629788418,
})
}
func (con DefaultController) News(c *gin.Context) {
//获取cookie
username, _ := c.Cookie("username")
c.String(200, "username=%v", username)
}
func (con DefaultController) Shop(c *gin.Context) {
//获取cookie
username, _ := c.Cookie("username")
c.String(200, "username=%v", username)
}
func (con DefaultController) DeleteCookie(c *gin.Context) {
//删除cookie
c.SetCookie("username", "张三", -1, "/", "localhost", false, true)
c.String(200, "删除成功")
}
package middlewares
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
)
func InitMiddleware(c *gin.Context) {
//判断用户是否登录
fmt.Println(time.Now())
fmt.Println(c.Request.URL)
c.Set("username", "张三")
//定义一个goroutine统计日志 当在中间件或 handler 中启动新的 goroutine 时,不能使用原始的上下文(c *gin.Context), 必须使用其只读副本(c.Copy())
cCp := c.Copy()
go func() {
time.Sleep(2 * time.Second)
fmt.Println("Done! in path " + cCp.Request.URL.Path)
}()
}
package models
import (
"time"
)
//时间戳转换成日期
func UnixToTime(timestamp int) string {
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 15:04:05")
}
//日期转换成时间戳 2020-05-02 15:04:05
func DateToUnix(str string) int64 {
template := "2006-01-02 15:04:05"
t, err := time.ParseInLocation(template, str, time.Local)
if err != nil {
return 0
}
return t.Unix()
}
//获取时间戳
func GetUnix() int64 {
return time.Now().Unix()
}
//获取当前的日期
func GetDate() string {
template := "2006-01-02 15:04:05"
return time.Now().Format(template)
}
//获取年月日
func GetDay() string {
template := "20060102"
return time.Now().Format(template)
}
package routers
import (
"gindemo12/controllers/admin"
"gindemo12/middlewares"
"github.com/gin-gonic/gin"
)
func AdminRoutersInit(r *gin.Engine) {
//middlewares.InitMiddleware中间件
adminRouters := r.Group("/admin", middlewares.InitMiddleware)
{
adminRouters.GET("/", admin.IndexController{}.Index)
adminRouters.GET("/user", admin.UserController{}.Index)
adminRouters.GET("/user/add", admin.UserController{}.Add)
adminRouters.POST("/user/doUpload", admin.UserController{}.DoUpload)
adminRouters.GET("/article", admin.ArticleController{}.Index)
adminRouters.GET("/article/add", admin.ArticleController{}.Add)
adminRouters.GET("/article/edit", admin.ArticleController{}.Edit)
}
}
package routers
import (
"gindemo12/controllers/api"
"github.com/gin-gonic/gin"
)
func ApiRoutersInit(r *gin.Engine) {
apiRouters := r.Group("/api")
{
apiRouters.GET("/", api.ApiController{}.Index)
apiRouters.GET("/userlist", api.ApiController{}.Userlist)
apiRouters.GET("/plist", api.ApiController{}.Plist)
}
}
package routers
import (
"gindemo12/controllers/itying"
"github.com/gin-gonic/gin"
)
func DefaultRoutersInit(r *gin.Engine) {
defaultRouters := r.Group("/")
{
defaultRouters.GET("/", itying.DefaultController{}.Index)
defaultRouters.GET("/news", itying.DefaultController{}.News)
defaultRouters.GET("/shop", itying.DefaultController{}.Shop)
defaultRouters.GET("/deleteCookie", itying.DefaultController{}.DeleteCookie)
}
}
{{ define "admin/index.html" }}
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<h2>这是后台首页</h2>
</body>
</html>
{{ end }}
{{ define "admin/news.html" }}
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<h2>后台新闻页面</h2>
</body>
</html>
{{ end }}
{{ define "admin/useradd.html" }}
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<h2>演示文件上传</h2>
<form action="/admin/user/doUpload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username" placeholder="用户名" />
<br>
<br>
头 像:<input type="file" name="face" />
<br> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
{{ end }}
<!-- 相当于给模板定义一个名字 define end 成对出现-->
{{ define "default/index.html" }}
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<link rel="stylesheet" href="/static/css/base.css">
</head>
<body>
<h1>我是一个首页--index</h1>
<br>
{{.msg}}
<br>
{{UnixToTime .t}}
</body>
</html>
{{ end }}
<!-- 相当于给模板定义一个名字 define end 成对出现-->
{{ define "default/user.html" }}
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<link rel="stylesheet" href="static/css/base.css">
</head>
<body>
<form action="/doAddUser2" method="post">
用户名:<input type="text" name="username" /> <br><br>
密码:<input type="password" name="password" /> <br><br>
<input type="submit" value="提交">
</form>
</body>
</html>
{{end}}
<!-- 相当于给模板定义一个名字 define end 成对出现-->
{{ define "public/page_footer.html" }}
<h1>
我是一个公共的底部
</h1>
{{end}}
<!-- 相当于给模板定义一个名字 define end 成对出现-->
{{ define "public/page_header.html" }}
<h1>
我是一个公共的标题---{{.title}}
</h1>
{{end}}
源码.7z