第一步:设置main 开启web服务
package main
import (
"ginproject1/route"
"net/http"
"time"
"golang.org/x/sync/errgroup"
)
var (
g errgroup.Group
)
func main() {
server01 := &http.Server{
Addr: ":9090",
Handler: route.Router01(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
server01.ListenAndServe()
}
第二部:创建route文件
package route
import (
"ginproject1/app/controller"
"io"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
//定义登录的中间件
func auth() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Query("token")
if token != "1" {
c.Abort() //终止挂起的程度,但是不会停止当前的处理程序,即代表程序可以继续往下走
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusBadRequest,
"error": "login failed",
}, //map类型的数据
)
} else {
c.Next() //只能在中间件中使用,调用处理程序的链中执行挂起的处理程序
}
}
}
func Router01() http.Handler {
gin.SetMode(gin.ReleaseMode)
gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)
}
//将数据写到日志文件中
f, _ := os.Create("runtime/gin.log")
gin.DefaultWriter = io.MultiWriter(f)
e := gin.New()
//设置模板和静态文件,最好放在调用中间件之前,否则加载的css.js文件则会出现也调用中间件报错
e.LoadHTMLGlob("app/template/*") //设置模板的路径
e.Static("/static", "static") //加载静态文件,将static文件夹中的文件都进行调用
e.Use(gin.Recovery()) //使用中间件
e.Use(auth()) //使用中间件
e.GET("/", func(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusOK,
"error": "Welcome server 01 1243",
}, //map类型的数据
)
})
e.GET("/log", func(c *gin.Context) {
log.Printf("%v", "hello world")
c.String(http.StatusOK, "logger") //输出字符串
})
e.POST("/addactivity", controller.AddActivity)
e.GET("/activitydetail/:id", controller.Activitydetail)
return e
}