-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (58 loc) · 1.55 KB
/
main.go
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
package main
import (
"fmt"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
"github.com/zwx19981207/Fastshorturl/credis"
"github.com/zwx19981207/Fastshorturl/uid"
"io/ioutil"
"log"
"net/url"
"strings"
"time"
)
var Credis = credis.RedisInit()
var Indexfile, _ = ioutil.ReadFile("templates/index.html")
func Shorturl(ctx *fasthttp.RequestCtx) {
shorturl := ctx.UserValue("shorturl").(string)
Dshorturl, _ := url.QueryUnescape(shorturl)
ret, err := Credis.HGet("url", Dshorturl).Result()
if err != nil {
fmt.Println(err)
ctx.SetBodyString("error")
} else {
ctx.Redirect(ret, fasthttp.StatusMovedPermanently)
}
}
func Index(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("text/html")
ctx.Response.SetBody(Indexfile)
}
func Postset(ctx *fasthttp.RequestCtx) {
key := uid.DecimalToAny(int(time.Now().UnixNano()), 76)
message := string(ctx.FormValue("url"))
if message == "" || strings.Index(message, "http") == -1 {
ctx.SetBodyString("error,请添加http://或https://")
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
return
}
_, err := Credis.HSet("url", key, message).Result()
if err != nil {
fmt.Println(err)
}
myurl, _ := credis.Cfg.GetValue("domain", "url")
if strings.Index(myurl, "http") == -1 {
ctx.SetBodyString("请输入正确的地址")
} else {
ctx.SetBodyString(myurl + key)
}
}
func main() {
router := fasthttprouter.New()
router.GET("/", Index)
router.GET("/:shorturl", Shorturl)
router.POST("/", Postset)
if Credis != nil {
log.Fatal(fasthttp.ListenAndServe(":88", router.Handler))
}
}