fathom/pkg/api/api.go

67 lines
1.2 KiB
Go
Raw Normal View History

package api
import (
"encoding/json"
2016-12-11 13:50:01 +00:00
"log"
"net/http"
"strconv"
2016-12-11 14:33:23 +00:00
"strings"
2016-12-11 13:50:01 +00:00
"time"
)
2016-12-04 12:23:09 +00:00
const defaultPeriod = 7
const defaultLimit = 10
type envelope struct {
Data interface{}
Error interface{}
}
func respond(w http.ResponseWriter, d interface{}) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
2017-01-15 15:12:14 +00:00
err := enc.Encode(d)
checkError(err)
}
2016-11-21 16:36:25 +00:00
// log fatal errors
func checkError(err error) {
2016-12-11 13:50:01 +00:00
if err != nil {
log.Fatal(err)
}
}
func getRequestedLimit(r *http.Request) int {
2016-12-11 13:50:01 +00:00
limit, err := strconv.Atoi(r.URL.Query().Get("limit"))
if err != nil || limit == 0 {
limit = 10
}
2016-12-11 13:50:01 +00:00
return limit
}
func getRequestedPeriods(r *http.Request) (int64, int64) {
2016-12-11 13:50:01 +00:00
var before, after int64
var err error
2016-12-11 13:50:01 +00:00
before, err = strconv.ParseInt(r.URL.Query().Get("before"), 10, 64)
if err != nil || before == 0 {
before = time.Now().Unix()
}
2016-12-11 13:50:01 +00:00
after, err = strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
if err != nil || before == 0 {
after = time.Now().AddDate(0, 0, -7).Unix()
}
2016-12-11 13:50:01 +00:00
return before, after
}
2016-12-11 14:33:23 +00:00
func parseMajorMinor(v string) string {
parts := strings.SplitN(v, ".", 3)
if len(parts) > 1 {
v = parts[0] + "." + parts[1]
}
return v
}