Created
June 29, 2015 21:52
-
-
Save anonymous/df5b4f560c4a9437b143 to your computer and use it in GitHub Desktop.
redis session keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ackage main | |
import "github.com/go-redis/redis" | |
import "github.com/go-martini/martini" | |
import "crypto/md5" | |
import "fmt" | |
var client *redis.Client | |
func main() { | |
m := martini.Classic() | |
m.Post("/login/:username", PostLogin) | |
m.Get("/test/:username/:sessionkey", GetTest) | |
client = connectToRedis() | |
m.Run() | |
} | |
func connectToRedis() *redis.Client { | |
client := redis.NewClient(&redis.Options{ | |
Addr: "localhost:6379", | |
Password: "", | |
DB: 0, | |
}) | |
_, err := client.Ping().Result() | |
if err != nil { | |
panic(err) | |
} else { | |
fmt.Println("Connected To Redis") | |
} | |
return client | |
} | |
func PostLogin(params martini.Params) (int, string) { | |
hash := md5.Sum([]byte(params["username"])) | |
fmt.Println("hash is", hash) | |
redisKey := fmt.Sprintf("session_keys:%s", params["username"]) | |
hashString := fmt.Sprintf("%x", hash) | |
err := client.Set(redisKey, hashString, 0).Err() | |
if err != nil { | |
return 500, "Internal Server Error" | |
} | |
return 200, hashString | |
} | |
func GetTest(params martini.Params) (int, string) { | |
hash := params["sessionkey"] | |
redisKey := fmt.Sprintf("session_keys:%s", params["username"]) | |
res, err := client.Get(redisKey).Result() | |
if err != nil { | |
return 500, "Internal Server Error" | |
} else if hash != res { | |
return 400, "Bad Request" | |
} else { | |
return 200, "OK" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment