2019-05-19 20:49:27 +03:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2021-04-16 16:59:39 +03:00
|
|
|
"github.com/muety/wakapi/config"
|
2022-10-16 19:59:19 +03:00
|
|
|
"github.com/muety/wakapi/models"
|
2019-05-19 20:49:27 +03:00
|
|
|
"net/http"
|
2022-04-18 12:39:26 +03:00
|
|
|
"regexp"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
2019-05-19 20:49:27 +03:00
|
|
|
)
|
|
|
|
|
2022-04-18 12:39:26 +03:00
|
|
|
const (
|
|
|
|
cacheMaxAgePattern = `max-age=(\d+)`
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
cacheMaxAgeRe *regexp.Regexp
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
cacheMaxAgeRe = regexp.MustCompile(cacheMaxAgePattern)
|
|
|
|
}
|
|
|
|
|
2021-04-26 22:26:47 +03:00
|
|
|
func RespondJSON(w http.ResponseWriter, r *http.Request, status int, object interface{}) {
|
2019-05-19 20:49:27 +03:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.WriteHeader(status)
|
|
|
|
if err := json.NewEncoder(w).Encode(object); err != nil {
|
2021-04-26 22:26:47 +03:00
|
|
|
config.Log().Request(r).Error("error while writing json response: %v", err)
|
2019-05-19 20:49:27 +03:00
|
|
|
}
|
|
|
|
}
|
2022-04-18 12:39:26 +03:00
|
|
|
|
|
|
|
func IsNoCache(r *http.Request, cacheTtl time.Duration) bool {
|
|
|
|
cacheControl := r.Header.Get("cache-control")
|
|
|
|
if strings.Contains(cacheControl, "no-cache") {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if match := cacheMaxAgeRe.FindStringSubmatch(cacheControl); match != nil && len(match) > 1 {
|
|
|
|
if maxAge, _ := strconv.Atoi(match[1]); time.Duration(maxAge)*time.Second <= cacheTtl {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2022-10-16 19:59:19 +03:00
|
|
|
|
|
|
|
func ParsePageParams(r *http.Request) *models.PageParams {
|
|
|
|
pageParams := &models.PageParams{}
|
|
|
|
page := r.URL.Query().Get("page")
|
|
|
|
pageSize := r.URL.Query().Get("page_size")
|
|
|
|
if p, err := strconv.Atoi(page); err == nil {
|
|
|
|
pageParams.Page = p
|
|
|
|
}
|
|
|
|
if p, err := strconv.Atoi(pageSize); err == nil && pageParams.Page > 0 {
|
|
|
|
pageParams.PageSize = p
|
|
|
|
}
|
|
|
|
return pageParams
|
|
|
|
}
|
2022-10-19 19:28:30 +03:00
|
|
|
|
|
|
|
func ParsePageParamsWithDefault(r *http.Request, page, size int) *models.PageParams {
|
|
|
|
pageParams := ParsePageParams(r)
|
|
|
|
if pageParams.Page == 0 {
|
|
|
|
pageParams.Page = page
|
|
|
|
}
|
|
|
|
if pageParams.PageSize == 0 {
|
|
|
|
pageParams.PageSize = size
|
|
|
|
}
|
|
|
|
return pageParams
|
|
|
|
}
|