drhib62644 2015-08-14 17:11
浏览 33
已采纳

戈朗的时间戳

Trying to get this approach to timestamps working in my application: https://gist.github.com/bsphere/8369aca6dde3e7b4392c#file-timestamp-go

Here it is:

package timestamp

import (
    "fmt"
    "labix.org/v2/mgo/bson"
    "strconv"
    "time"
)

type Timestamp time.Time

func (t *Timestamp) MarshalJSON() ([]byte, error) {
    ts := time.Time(*t).Unix()
    stamp := fmt.Sprint(ts)

    return []byte(stamp), nil
}

func (t *Timestamp) UnmarshalJSON(b []byte) error {
    ts, err := strconv.Atoi(string(b))
    if err != nil {
        return err
    }

    *t = Timestamp(time.Unix(int64(ts), 0))

    return nil
}

func (t Timestamp) GetBSON() (interface{}, error) {
    if time.Time(*t).IsZero() {
        return nil, nil
    }

    return time.Time(*t), nil
}

func (t *Timestamp) SetBSON(raw bson.Raw) error {
    var tm time.Time

    if err := raw.Unmarshal(&tm); err != nil {
        return err
    }

    *t = Timestamp(tm)

    return nil
}

func (t *Timestamp) String() string {
    return time.Time(*t).String()
}

and the article that goes with it: https://medium.com/coding-and-deploying-in-the-cloud/time-stamps-in-golang-abcaf581b72f

However, I'm getting the following error:

core/timestamp/timestamp.go:31: invalid indirect of t (type Timestamp)                                                                                                                                                     
core/timestamp/timestamp.go:35: invalid indirect of t (type Timestamp)

My relevant code looks like this:

import (
    "github.com/path/to/timestamp"
)

type User struct {
    Name        string
    Created_at  *timestamp.Timestamp  `bson:"created_at,omitempty" json:"created_at,omitempty"`
} 

Can anyone see what I'm doing wrong?

Related question I can't see how to implement this package either. Do I create a new User model something like this?

u := User{Name: "Joe Bloggs", Created_at: timestamp.Timestamp(time.Now())}
  • 写回答

2条回答 默认 最新

  • dragonsun00000 2015-08-14 17:56
    关注

    Your code has a typo. You can't dereference a non-pointer, so you need to make GetBSON a pointer receiver (or you could remove the indirects to t, since the value of t isn't changed by the method).

    func (t *Timestamp) GetBSON() (interface{}, error) {
    

    To set a *Timestamp value inline, you need to have a *time.Time to convert.

    now := time.Now()
    u := User{
        Name:      "Bob",
        CreatedAt: (*Timestamp)(&now),
    }
    

    Constructor and a helper functions like New() and Now() may come in handy for this as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100