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

    源码.7z