package main

import (
    "github.com/gin-gonic/gin"
    "time"
    "log"
)

func main()  {
    // 初始化
    router := gin.New();

    // 常规操作
    router.POST("/", func(context *gin.Context) {
        context.JSON(200,"POST")
    })
    router.GET("/", func(context *gin.Context) {
        context.JSON(200,"GET")
    })
    router.DELETE("/", func(context *gin.Context) {
        context.JSON(200,"DELETE")
    })
    router.PATCH("/", func(context *gin.Context) {
        context.JSON(200,"PATCH")
    })
    router.PUT("/", func(context *gin.Context) {
        context.JSON(200,"PUT")
    })
    router.OPTIONS("/", func(context *gin.Context) {
        context.JSON(200,"OPTIONS")
    })
    router.HEAD("/", func(context *gin.Context) {
        context.JSON(200,"HEAD")
    })
    // 多方式匹配
    // 包括 GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE
    router.Any("/", func(context *gin.Context) {
        context.JSON(200,"Any")
    })
    // 参数 GET, POST, PUT, PATCH, DELETE
    router.Handle("GET","/", func(context *gin.Context) {
        context.JSON(200,"GET")
    })

    // 未知路由处理
    router.NoRoute(func(context *gin.Context) {
        context.String(404,"Not router")
    })
    // 未知调用方式
    router.NoMethod(func(context *gin.Context) {
        context.String(404,"Not method")
    })

    // 静态资源返回
    router.StaticFile("favicon.ico", "./resources/favicon.ico")
    // 静态资源目录
    router.Static("/css", "/var/www/css")

    // GROUP
    // 接口版本前缀
    group := router.Group("/v1")
    group.GET("user/info", func(context *gin.Context) {
        context.String(200,"username")
    })

    // Middleware
    middleware := router.Group("", func(context *gin.Context) {
        name := context.Query("name")
        if(name=="admin"){
            context.Redirect(302,"/home")
        }
        context.String(403,"Unauthorized")
    })
    middleware.GET("/home", func(context *gin.Context) {
        context.String(200,"Api home")
    })

    // 全局监控
    loger := router.Use(func(context *gin.Context) {
        t := time.Now()
        context.Set("username", "admin")
        // before request

        context.Next()

        // after request
        latency := time.Since(t)
        log.Print(latency)

        // access the status we are sending
        status := context.Writer.Status()
        log.Println(status)
    })
    loger.GET("/update", func(context *gin.Context) {
        context.String(200,"Success")
    })

    // 启动服务
    router.Run(":8080")
}