Files
learngo/interfaces/composition/book.go

52 lines
820 B
Go
Raw Normal View History

// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
2019-08-27 15:21:17 +03:00
import (
2019-08-30 00:49:27 +03:00
"encoding/json"
2019-08-27 15:21:17 +03:00
"fmt"
"strconv"
"time"
)
type book struct {
2019-08-30 00:49:27 +03:00
product
Published interface{}
}
2019-08-27 15:21:17 +03:00
func (b *book) String() string {
2019-08-30 00:49:27 +03:00
p := format(b.Published)
return fmt.Sprintf("%s - (%v)", &b.product, p)
}
func (b *book) MarshalJSON() ([]byte, error) {
type jbook book
jb := (*jbook)(b)
jb.Published = format(b.Published)
return json.Marshal(jb)
}
2019-08-27 15:21:17 +03:00
func format(v interface{}) string {
var t int
switch v := v.(type) {
case int:
t = v
case string:
t, _ = strconv.Atoi(v)
default:
return "unknown"
}
const layout = "2006/01"
u := time.Unix(int64(t), 0)
return u.Format(layout)
}