github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/swarm/storage/feed/timestampprovider.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:44</date>
    10  //</624450119500042240>
    11  
    12  
    13  package feed
    14  
    15  import (
    16  	"encoding/json"
    17  	"time"
    18  )
    19  
    20  //TimestampProvider设置源包的时间源
    21  var TimestampProvider timestampProvider = NewDefaultTimestampProvider()
    22  
    23  //timestamp将时间点编码为unix epoch
    24  type Timestamp struct {
    25  Time uint64 `json:"time"` //unix epoch时间戳(秒)
    26  }
    27  
    28  //TimestampProvider接口描述时间戳信息的来源
    29  type timestampProvider interface {
    30  Now() Timestamp //返回当前时间戳信息
    31  }
    32  
    33  //unmashaljson实现json.unmarshaller接口
    34  func (t *Timestamp) UnmarshalJSON(data []byte) error {
    35  	return json.Unmarshal(data, &t.Time)
    36  }
    37  
    38  //marshaljson实现json.marshaller接口
    39  func (t *Timestamp) MarshalJSON() ([]byte, error) {
    40  	return json.Marshal(t.Time)
    41  }
    42  
    43  //DefaultTimestampProvider是使用系统时间的TimestampProvider
    44  //作为时间来源
    45  type DefaultTimestampProvider struct {
    46  }
    47  
    48  //NewDefaultTimestampProvider创建基于系统时钟的时间戳提供程序
    49  func NewDefaultTimestampProvider() *DefaultTimestampProvider {
    50  	return &DefaultTimestampProvider{}
    51  }
    52  
    53  //现在根据此提供程序返回当前时间
    54  func (dtp *DefaultTimestampProvider) Now() Timestamp {
    55  	return Timestamp{
    56  		Time: uint64(time.Now().Unix()),
    57  	}
    58  }
    59