/
base.go
76 lines (60 loc) · 1.56 KB
/
base.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
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2016 The StudyGolang Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// http://studygolang.com
// Author: polaris polaris@studygolang.com
package controller
import (
"encoding/json"
"net/http"
"strings"
"sander/db/nosql"
xhttp "sander/http"
"sander/logger"
"github.com/labstack/echo"
"github.com/polaris1119/goutils"
)
// render html 输出
func render(ctx echo.Context, contentTpl string, data map[string]interface{}) error {
return xhttp.Render(ctx, contentTpl, data)
}
func success(ctx echo.Context, data interface{}) error {
result := map[string]interface{}{
"ok": 1,
"msg": "操作成功",
"data": data,
}
b, err := json.Marshal(result)
if err != nil {
return err
}
oldETag := ctx.Request().Header().Get("If-None-Match")
if strings.HasPrefix(oldETag, "W/") {
oldETag = oldETag[2:]
}
newETag := goutils.Md5Buf(b)
if oldETag == newETag {
return ctx.NoContent(http.StatusNotModified)
}
go func(b []byte) {
if cacheKey := ctx.Get(nosql.CacheKey); cacheKey != nil {
nosql.DefaultLRUCache.CompressAndAdd(cacheKey, b, nosql.NewCacheData())
}
}(b)
if ctx.Response().Committed() {
return nil
}
ctx.Response().Header().Add("ETag", newETag)
return ctx.JSONBlob(http.StatusOK, b)
}
func fail(ctx echo.Context, code int, msg string) error {
if ctx.Response().Committed() {
return nil
}
result := map[string]interface{}{
"ok": 0,
"error": msg,
}
logger.Error("operate fail:%+v", result)
return ctx.JSON(http.StatusOK, result)
}