Refactor time usages (use Format instead of String)

This commit is contained in:
Jan-Lukas Else 2021-07-13 17:23:10 +02:00
parent fe825e4778
commit ea00ff5788
8 changed files with 74 additions and 34 deletions

View File

@ -70,6 +70,9 @@ func (a *goBlog) openDatabase(file string, logging bool) (*database, error) {
if err := c.RegisterFunc("tolocal", toLocalSafe, true); err != nil {
return err
}
if err := c.RegisterFunc("toutc", toUTCSafe, true); err != nil {
return err
}
if err := c.RegisterFunc("wordcount", wordCount, true); err != nil {
return err
}

View File

@ -219,10 +219,29 @@ func migrateDb(db *sql.DB, logging bool) error {
return err
},
},
&migrator.Migration{
Name: "00018",
Func: func(tx *sql.Tx) error {
_, err := tx.Exec(`
update queue set schedule = toutc(schedule);
update persistent_cache set date = toutc(date);
update sessions set created = toutc(created), modified = toutc(modified), expires = toutc(expires);
`)
return err
},
},
),
)
if err != nil {
return err
}
return m.Migrate(db)
err = m.Migrate(db)
if err != nil {
return err
}
// Update times in database to local time
_, err = db.Exec(`
update posts set published = tolocal(published), updated = tolocal(updated);
`)
return err
}

View File

@ -91,10 +91,10 @@ func (a *goBlog) indieAuthAccept(w http.ResponseWriter, r *http.Request) {
RedirectURI: r.Form.Get("redirect_uri"),
State: r.Form.Get("state"),
Scopes: r.Form["scopes"],
time: time.Now(),
time: time.Now().UTC(),
}
sha := sha1.New()
if _, err := sha.Write([]byte(data.time.String() + data.ClientID)); err != nil {
if _, err := sha.Write([]byte(data.time.Format(time.RFC3339) + data.ClientID)); err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
@ -190,9 +190,9 @@ func (a *goBlog) indieAuthToken(w http.ResponseWriter, r *http.Request) {
a.serveError(w, r, "No scope", http.StatusBadRequest)
return
}
data.time = time.Now()
data.time = time.Now().UTC()
sha := sha1.New()
if _, err := sha.Write([]byte(data.time.String() + data.ClientID)); err != nil {
if _, err := sha.Write([]byte(data.time.Format(time.RFC3339) + data.ClientID)); err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}

View File

@ -11,7 +11,6 @@ import (
"regexp"
"strconv"
"strings"
"time"
"github.com/spf13/cast"
"go.goblog.app/app/pkgs/contenttype"
@ -370,7 +369,7 @@ func (a *goBlog) computeExtraPostParameters(p *post) error {
}
if p.Published == "" && p.Section != "" {
// Has no published date, but section -> published now
p.Published = time.Now().Local().String()
p.Published = localNowString()
}
// Add images not in content
images := p.Parameters[a.cfg.Micropub.PhotoParam]

View File

@ -2,12 +2,10 @@ package main
import (
"database/sql"
"time"
)
func (db *database) cachePersistently(key string, data []byte) error {
date, _ := toLocal(time.Now().String())
_, err := db.exec("insert or replace into persistent_cache(key, data, date) values(@key, @data, @date)", sql.Named("key", key), sql.Named("data", data), sql.Named("date", date))
_, err := db.exec("insert or replace into persistent_cache(key, data, date) values(@key, @data, @date)", sql.Named("key", key), sql.Named("data", data), sql.Named("date", utcNowString()))
return err
}

View File

@ -8,15 +8,6 @@ import (
"github.com/araddon/dateparse"
)
func (db *database) enqueue(name string, content []byte, schedule time.Time) error {
if len(content) == 0 {
return errors.New("empty content")
}
_, err := db.exec("insert into queue (name, content, schedule) values (@name, @content, @schedule)",
sql.Named("name", name), sql.Named("content", content), sql.Named("schedule", schedule.UTC().String()))
return err
}
type queueItem struct {
id int
name string
@ -24,8 +15,17 @@ type queueItem struct {
schedule *time.Time
}
func (db *database) enqueue(name string, content []byte, schedule time.Time) error {
if len(content) == 0 {
return errors.New("empty content")
}
_, err := db.exec("insert into queue (name, content, schedule) values (@name, @content, @schedule)",
sql.Named("name", name), sql.Named("content", content), sql.Named("schedule", schedule.UTC().Format(time.RFC3339)))
return err
}
func (db *database) reschedule(qi *queueItem, dur time.Duration) error {
_, err := db.exec("update queue set schedule = @schedule, content = @content where id = @id", sql.Named("schedule", qi.schedule.Add(dur).UTC().String()), sql.Named("content", qi.content), sql.Named("id", qi.id))
_, err := db.exec("update queue set schedule = @schedule, content = @content where id = @id", sql.Named("schedule", qi.schedule.Add(dur).UTC().Format(time.RFC3339)), sql.Named("content", qi.content), sql.Named("id", qi.id))
return err
}
@ -35,23 +35,22 @@ func (db *database) dequeue(qi *queueItem) error {
}
func (db *database) peekQueue(name string) (*queueItem, error) {
row, err := db.queryRow("select id, name, content, schedule from queue where schedule <= @schedule and name = @name order by schedule asc limit 1", sql.Named("name", name), sql.Named("schedule", time.Now().UTC().String()))
row, err := db.queryRow("select id, name, content, schedule from queue where schedule <= @schedule and name = @name order by schedule asc limit 1", sql.Named("name", name), sql.Named("schedule", time.Now().UTC().Format(time.RFC3339)))
if err != nil {
return nil, err
}
qi := &queueItem{}
var timeString string
if err = row.Scan(&qi.id, &qi.name, &qi.content, &timeString); err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, err
}
t, err := dateparse.ParseLocal(timeString)
t, err := dateparse.ParseIn(timeString, time.UTC)
if err != nil {
return nil, err
}
t = t.Local()
qi.schedule = &t
return qi, nil
}

View File

@ -21,8 +21,10 @@ const (
func (a *goBlog) initSessions() {
deleteExpiredSessions := func() {
if _, err := a.db.exec("delete from sessions where expires < @now",
sql.Named("now", time.Now().Local().String())); err != nil {
if _, err := a.db.exec(
"delete from sessions where expires < @now",
sql.Named("now", utcNowString()),
); err != nil {
log.Println("Failed to delete expired sessions:", err.Error())
}
}
@ -135,9 +137,9 @@ func (s *dbSessionStore) load(session *sessions.Session) (err error) {
}
func (s *dbSessionStore) insert(session *sessions.Session) (err error) {
created := time.Now()
modified := time.Now()
expires := time.Now().Add(time.Second * time.Duration(session.Options.MaxAge))
created := time.Now().UTC()
modified := time.Now().UTC()
expires := time.Now().UTC().Add(time.Second * time.Duration(session.Options.MaxAge))
delete(session.Values, sessionCreatedOn)
delete(session.Values, sessionExpiresOn)
delete(session.Values, sessionModifiedOn)
@ -146,7 +148,7 @@ func (s *dbSessionStore) insert(session *sessions.Session) (err error) {
return err
}
res, err := s.db.exec("insert into sessions(data, created, modified, expires) values(@data, @created, @modified, @expires)",
sql.Named("data", encoded), sql.Named("created", created.Local().String()), sql.Named("modified", modified.Local().String()), sql.Named("expires", expires.Local().String()))
sql.Named("data", encoded), sql.Named("created", created.Format(time.RFC3339)), sql.Named("modified", modified.Format(time.RFC3339)), sql.Named("expires", expires.Format(time.RFC3339)))
if err != nil {
return err
}
@ -170,7 +172,7 @@ func (s *dbSessionStore) save(session *sessions.Session) (err error) {
return err
}
_, err = s.db.exec("update sessions set data = @data, modified = @modified where id = @id",
sql.Named("data", encoded), sql.Named("modified", time.Now().Local().String()), sql.Named("id", session.ID))
sql.Named("data", encoded), sql.Named("modified", utcNowString()), sql.Named("id", session.ID))
if err != nil {
return err
}

View File

@ -132,7 +132,23 @@ func toLocal(s string) (string, error) {
if err != nil {
return "", err
}
return d.Local().String(), nil
return d.Local().Format(time.RFC3339), nil
}
func toUTCSafe(s string) string {
d, _ := toUTC(s)
return d
}
func toUTC(s string) (string, error) {
if s == "" {
return "", nil
}
d, err := dateparse.ParseLocal(s)
if err != nil {
return "", err
}
return d.UTC().Format(time.RFC3339), nil
}
func dateFormat(date string, format string) string {
@ -148,11 +164,15 @@ func isoDateFormat(date string) string {
}
func unixToLocalDateString(unix int64) string {
return time.Unix(unix, 0).Local().String()
return time.Unix(unix, 0).Local().Format(time.RFC3339)
}
func localNowString() string {
return time.Now().Local().String()
return time.Now().Local().Format(time.RFC3339)
}
func utcNowString() string {
return time.Now().UTC().Format(time.RFC3339)
}
type stringPair struct {