89 lines
1.5 KiB
Go
89 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
e "git.xdrm.io/go/xb-api/err"
|
|
i "git.xdrm.io/go/xb-api/implement"
|
|
r "github.com/go-redis/redis"
|
|
)
|
|
|
|
// Initiates connection to redis dataset
|
|
func redisConnect() (*r.Client, error) {
|
|
cli := r.NewClient(&r.Options{
|
|
Addr: "127.0.0.1:6379",
|
|
Password: "",
|
|
DB: 0,
|
|
})
|
|
|
|
_, err := cli.Ping().Result()
|
|
|
|
return cli, err
|
|
}
|
|
|
|
// Redirects to an url from a key
|
|
func Get(d i.Arguments, r *i.Response) i.Response {
|
|
|
|
/* (1) Init redis connection */
|
|
cli, err := redisConnect()
|
|
if err != nil {
|
|
r.Err = e.Failure
|
|
return *r
|
|
}
|
|
|
|
/* (2) Extract api input */
|
|
key, ok := d["url"].(string)
|
|
|
|
if !ok {
|
|
r.Err = e.InvalidParam
|
|
r.Err.BindArgument("url")
|
|
return *r
|
|
}
|
|
|
|
/* (3) Check if match for this key */
|
|
val, err := cli.Get(key).Result()
|
|
if err != nil {
|
|
r.Err = e.NoMatchFound
|
|
return *r
|
|
}
|
|
|
|
/* (4) Redirect to value */
|
|
r.Set("_REDIRECT_", val)
|
|
r.Err = e.Success
|
|
return *r
|
|
}
|
|
|
|
// Stores a new tinyurl/fullurl combination
|
|
func Post(d i.Arguments, r *i.Response) i.Response {
|
|
/* (1) Init redis connection */
|
|
cli, err := redisConnect()
|
|
if err != nil {
|
|
r.Err = e.Failure
|
|
return *r
|
|
}
|
|
|
|
/* (2) Extract api input */
|
|
target, ok1 := d["target"].(string)
|
|
url, ok2 := d["url"].(string)
|
|
|
|
if !ok1 || !ok2 {
|
|
r.Err = e.InvalidParam
|
|
return *r
|
|
}
|
|
|
|
/* (3) Check if key already used */
|
|
_, err = cli.Get(url).Result()
|
|
if err == nil {
|
|
r.Err = e.AlreadyExists
|
|
return *r
|
|
}
|
|
|
|
/* (4) Store */
|
|
err = cli.Set(url, target, 0).Err()
|
|
if err != nil {
|
|
r.Err = e.Failure
|
|
return *r
|
|
}
|
|
|
|
r.Err = e.Success
|
|
return *r
|
|
}
|