package main
import (
"github.com/gin-gonic/gin"
"github.com/gomodule/redigo/redis"
"log"
)
var redisPool *redis.Pool
var err error
func main() {
redisPool = RedisPollInit()
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.GET("/", IndexAction)
r.GET("/ping", PingAction)
r.GET("/user/:name", UserAction)
r.GET("/agent", AgentAction)
r.GET("/admin", AdminAction)
r.Run(":80")
}
func RedisPollInit() *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
MaxActive: 5,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
return nil, err
}
_, err = c.Do("AUTH", "123456")
if err != nil {
c.Close()
return nil, err
}
return c, err
},
}
}
func IndexAction(c *gin.Context) {
c.JSON(200, gin.H{"message": "index"})
}
func PingAction(c *gin.Context) {
c.JSON(200, gin.H{"message": "pong"})
}
func UserAction(c *gin.Context) {
c.String(200, "Hello %s", c.Param("name"))
}
func AgentAction(c *gin.Context) {
c.String(200, c.GetHeader("user-agent"))
}
func AdminAction(c *gin.Context) {
conn := redisPool.Get()
defer conn.Close()
data, err := redis.String(conn.Do("GET", "username"))
if err != nil {
log.Println(err)
return
}
c.String(200, data)
}