-
Notifications
You must be signed in to change notification settings - Fork 0
/
basehandler.go
57 lines (47 loc) · 1.85 KB
/
basehandler.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
package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/howood/imagereductor/application/actor/storageservice"
"github.com/howood/imagereductor/infrastructure/requestid"
"github.com/howood/imagereductor/library/utils"
"github.com/labstack/echo/v4"
)
const marshalPrefix = ""
const marshalIndent = " "
// BaseHandler struct
type BaseHandler struct {
ctx context.Context
}
func (bh BaseHandler) errorResponse(c echo.Context, statudcode int, err error) error {
if strings.Contains(strings.ToLower(err.Error()), storageservice.RecordNotFoundMsg) {
statudcode = http.StatusNotFound
}
c.Response().Header().Set(echo.HeaderXRequestID, fmt.Sprintf("%v", bh.ctx.Value(requestid.GetRequestIDKey())))
return c.JSONPretty(statudcode, map[string]interface{}{"message": err.Error()}, marshalIndent)
}
func (bh BaseHandler) setResponseHeader(c echo.Context, lastmodified, contentlength string, expires, xrequestid string) {
c.Response().Header().Set(echo.HeaderLastModified, lastmodified)
c.Response().Header().Set(echo.HeaderContentLength, contentlength)
c.Response().Header().Set(echo.HeaderXRequestID, xrequestid)
c.Response().Header().Set("Cache-Control", fmt.Sprintf("max-age:%g, public", (bh.getHeaderExpires()*time.Second).Seconds()))
if expires != "" {
c.Response().Header().Set("Expires", expires)
}
}
func (bh BaseHandler) setNewLatsModified() string {
return time.Now().UTC().Format(http.TimeFormat)
}
func (bh BaseHandler) setExpires(epires time.Time) string {
return epires.Add(bh.getHeaderExpires() * time.Second).UTC().Format(http.TimeFormat)
}
func (bh BaseHandler) getHeaderExpires() time.Duration {
return time.Duration(utils.GetOsEnvInt("HEADEREXPIRED", 300))
}
func (bh BaseHandler) jsonToByte(jsondata interface{}) ([]byte, error) {
return json.MarshalIndent(jsondata, marshalPrefix, marshalIndent)
}