编组时间.unix时间戳记的时间

I have a struct like so

type log struct {
    [...]
    Timestamp timestamp `json:"timestamp"`
}

and I want to have the Timestamp as unix timestamp instead of whatever go does by default (2018-09-21T19:31:03.291Z)

I've tried creating a custom type for that like this:

type timestamp struct {
    time.Time
}

func (t timestamp) MarshalJSON() ([]byte, error) {
    return []byte(strconv.FormatInt(time.Time(t.Time).Unix(), 10)), nil
}

func (t *timestamp) UnmarshalJSON(data []byte) error {
    i, err := strconv.ParseInt(string(data[:]), 10, 64)
    if err != nil {
        return err
    }
    t = &timestamp{
        time.Unix(i, 0),
    }
    return nil
}

but I'm always getting the error can not unmarshal timestamp into *main.timestamp when trying to read from the database.

for iter.Scan(&message.Text, &message.Timestamp) {

    userlogResult.Messages = append(userlogResult.Messages, message)
}
if err := iter.Close(); err != nil {
    log.Error(err)
}

It can't unmarshall the Timestamp here. https://github.com/gocql/gocql/blob/799fb0373110eaa4e2e71dd32a9b5903f80dca8f/helpers.go#L30 the issue is that it doesn't use the Unmarshall functions.

Edit: I've answered my own question.

here when assigning &timestamp{..} to t it is changing the pointer instead the value it is pointed to has to be chaged as follows

func (t *timestamp) UnmarshalJSON(data []byte) error {
    i, err := strconv.ParseInt(string(data[:]), 10, 64)
    if err != nil {
        return err
    }
    *t = timestamp{
        time.Unix(i, 0),
    }
    return nil
}

Please find code here

Edit

Since you are failing to unmarshall when reading from Database it is not because of json.unmarshalling you have to implement sql.Scanner if you are using sql

Please find the details here => sql.Scanner

I think your code is ok - apart from the code in your unmarshal. You don't show the code where you are Marshalling/Unmarshalling which is where the actual error is.

I have it working on the playground. Golang Playground

Instead of this (which changes the pointer)

t = &timestamp{
  time.Unix(i, 0),
}

Change the value

t.Time = time.Unix(i,0)

Main function to use your structs

fmt.Println("First Log...")
l := log{Timestamp: timestamp{time.Now()}}
fmt.Println(l)

buf, err := json.Marshal(l)
if err != nil {
    panic(err)
}
fmt.Println("Marshalled to JSON...")
fmt.Printf("%s
", buf)

var logCopy log
if err := json.Unmarshal(buf, &logCopy); err != nil {
    panic(err)
}
fmt.Println("UnMarshalled from JSON...")
fmt.Println(logCopy)

Alright after confusing a lot of people here (sorry) and myself I've found a solution.

The marshalling to json works now only need to fix the gocql compatiblity like this:

var ts time.Time
for iter.Scan(&message.Text, &ts) {
    message.Timestamp = timestamp{ts}

    userlogResult.Messages = append(userlogResult.Messages, message)
}