1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package main
import ( "flag" "fmt" "github.com/garyburd/redigo/redis" "github.com/gin-gonic/gin"
"net/http" )
var port string var pwd string var pool *redis.Pool
func init() { pool = &redis.Pool{ MaxIdle: 16, MaxActive: 0, IdleTimeout: 300, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", "localhost:6379") }, } }
func main() { flag.StringVar(&port, "P", "80", "port,default 80") flag.StringVar(&pwd, "PWD", "JMqU25yVuS8cDd0B", "password,default JMqU25yVuS8cDd0B") flag.Parse() apiServer := gin.New() apiServer.GET("/", Index) apiServer.GET("/hello", HelloWorldGet) apiServer.POST("/hello", HelloWorldPost) portString := fmt.Sprintf(":%s", port) apiServer.Run(portString) }
func Index(context *gin.Context) { indexHtml := `<!DOCTYPE html> <html> <title>submit Relut</title> <h1>Submit Relut</h1> <form action="/hello" method="post"> saveKey:<input type="text" name="saveKey"><br> Relut:<input type="text" name="result"><br> <input type="submit" value="submit"> </form> </html>` context.Header("Content-Type", "text/html; charset=utf-8") context.String(http.StatusOK, indexHtml) }
func HelloWorldGet(context *gin.Context) { getKey := context.Query("key") passwd := context.Query("pwd") ip := context.ClientIP() if passwd != pwd { context.IndentedJSON(http.StatusBadRequest, gin.H{ "Error": "PASSWD", "IP": ip, }) return }
c := pool.Get() defer c.Close() ret, err := c.Do("SPOP", getKey, context.Query("num")) if err != nil { fmt.Printf("Ip: %s,srandmember get failed.\n", ip) } else { fmt.Printf("Ip: %s srandmember get value is:%s\n", ip, ret) }
num, err := c.Do("scard", getKey) if err != nil { fmt.Println("scard error", err.Error()) } else { fmt.Println("scard get num :", num) }
context.IndentedJSON(http.StatusOK, gin.H{ "domain": fmt.Sprintf("%s", ret), "num": num, }) }
func HelloWorldPost(context *gin.Context) { result := context.PostForm("result") key := context.PostForm("saveKey") ip := context.ClientIP() c := pool.Get() defer c.Close()
_, err := redis.Int(c.Do("sadd", key, result)) if err != nil { fmt.Println("set add failed", err.Error()) } else { fmt.Printf("Ip: %s,add Data Success.\n", ip) }
num, err := c.Do("scard", key) if err != nil { fmt.Println("scard error", err.Error()) } else { fmt.Println("scard get num :", num) }
context.JSON(http.StatusOK, gin.H{ "success": num, })
}
|