tiny-url-ex/root/i.go

143 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
2018-07-07 21:41:25 +00:00
"git.xdrm.io/example/aicra/root/db"
2018-07-05 17:19:39 +00:00
e "git.xdrm.io/go/aicra/err"
i "git.xdrm.io/go/aicra/implement"
)
2018-06-16 16:04:28 +00:00
// Redirects to an url from a key
func Get(d i.Arguments, r *i.Response) i.Response {
2018-06-16 16:04:28 +00:00
/* (1) Init redis connection */
cli := db.Connect()
if cli == nil {
2018-06-16 16:04:28 +00:00
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 := cli.Get(key)
if val == nil {
2018-06-16 16:04:28 +00:00
r.Err = e.NoMatchFound
return *r
}
/* (4) Redirect to value */
r.Set("_REDIRECT_", string(val))
2018-06-16 16:04:28 +00:00
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 := db.Connect()
if cli == nil {
2018-06-16 16:04:28 +00:00
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 */
if cli.Get(url) != nil {
2018-06-16 16:04:28 +00:00
r.Err = e.AlreadyExists
return *r
}
/* (4) Store */
if !cli.Set(url, target) {
r.Err = e.Failure
return *r
}
r.Err = e.Success
return *r
}
// Overrides a existing tinyurl with new target
func Put(d i.Arguments, r *i.Response) i.Response {
/* (1) Init redis connection */
cli := db.Connect()
if cli == 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 */
if cli.Get(url) == nil {
r.Err = e.NoMatchFound
return *r
}
/* (4) Update */
if !cli.Set(url, target) {
r.Err = e.Failure
return *r
}
r.Err = e.Success
return *r
}
// Deletes an existing tinyurl
func Delete(d i.Arguments, r *i.Response) i.Response {
/* (1) Init redis connection */
cli := db.Connect()
if cli == nil {
r.Err = e.Failure
return *r
}
/* (2) Extract api input */
url, ok := d["url"].(string)
if !ok {
r.Err = e.InvalidParam
return *r
}
/* (3) Check if key already used */
if cli.Get(url) == nil {
r.Err = e.NoMatchFound
return *r
}
/* (4) Delete */
if !cli.Del(url) {
2018-06-16 16:04:28 +00:00
r.Err = e.Failure
return *r
}
r.Err = e.Success
return *r
}