Skip to content

Instantly share code, notes, and snippets.

@dmigo
Created May 8, 2019 21:20
Show Gist options
  • Save dmigo/2f127c7170cc8e16cf19cc466a7852ec to your computer and use it in GitHub Desktop.
Save dmigo/2f127c7170cc8e16cf19cc466a7852ec to your computer and use it in GitHub Desktop.
Example of gin application calling redis
package main
import "github.com/gin-gonic/gin"
import "fmt"
import "github.com/go-redis/redis"
func ExampleNewClient() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
// Output: PONG <nil>
}
func ExampleClient() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
err := client.Set("key", "value", 0).Err()
if err != nil {
panic(err)
}
val, err := client.Get("key").Result()
if err != nil {
panic(err)
}
fmt.Println("key", val)
val2, err := client.Get("key2").Result()
if err == redis.Nil {
fmt.Println("key2 does not exist")
} else if err != nil {
panic(err)
} else {
fmt.Println("key2", val2)
}
// Output: key value
// key2 does not exist
}
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/redis", func(c *gin.Context) {
ExampleClient()
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment