-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.go
55 lines (46 loc) · 1.26 KB
/
create.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
package handlers
import (
"fmt"
"strings"
"time"
"github.com/valyala/fasthttp"
"github.com/zj0395/golib/fhlib"
"github.com/zj0395/golib/liberr"
"github.com/zj0395/urlshortener/models"
"github.com/zj0395/urlshortener/utils/shorten"
)
func Create(ctx *fasthttp.RequestCtx) {
logger := fhlib.GetLogger(ctx)
url := strings.TrimSpace(string(ctx.QueryArgs().Peek("url")))
if url == "" {
logger.Error().Str("error", "empty url").Msg("Create shorturl error")
fhlib.SetError(ctx, liberr.ParamError)
return
}
// insert db
obj := models.UrlShorten{
Url: url,
Ip: fhlib.ClientIP(ctx),
Ctime: time.Now().Unix(),
}
dbRes := models.DBTx(models.GetUrlShortenTable(url)).Create(&obj)
if dbRes.Error != nil {
logger.Error().Str("error", dbRes.Error.Error()).Msg("Create shorturl error")
fhlib.SetError(ctx, dbRes.Error)
return
}
if dbRes.RowsAffected == 0 {
logger.Error().Msg("Create shorturl fail, affectet row = 0")
fhlib.SetError(ctx, liberr.DBError)
return
}
// idshorten
code := shorten.IDShorten(obj.ID)
logger.Info().Int64("id", obj.ID).Str("code", code).Msg("Create url succ")
host := ctx.Request.Header.Host()
resp := map[string]interface{}{
"code": code,
"surl": fmt.Sprintf("%s/%s", host, code),
}
fhlib.SetData(ctx, resp)
}