Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Ну про что может быть первый комментарий к статье про Go? Правильно! Про Rust!
А что со скоростью?
toJson func() (data []byte, err error)
return json.Marshal(&struct {
Id int64 `json:"ref"`
Title string `json:"title"`
Description string `json:"description"`
PromoPrice int64 `json:"price"`
PromoDescription string `json:"promo,omitempty"`
Links Links `json:"links"`
}{
Id: b.Id,
Title: b.Title,
Description: b.Description,
PromoPrice: b.PromoPrice,
PromoDescription: b.PromoDescription,
Links: b.Links,
})
package models
import (
"encoding/json"
"fmt"
"time"
)
const (
SiteBook1View = iota
Partner1Book1View
Partner2Book1View
PromoBook1View
)
func (b *Book1) SetDefaultView() {
b.SetSiteView()
}
func (b *Book1) SetSiteView() {
b.view = SiteBook1View
}
func (b *Book1) SetPartner1View() {
b.view = Partner1Book1View
}
func (b *Book1) SetPartner2View() {
b.view = Partner2Book1View
}
func (b *Book1) SetPromoView() {
b.view = PromoBook1View
}
type Book1 struct {
Id int64
Title string
Description string
Partner2Title string
Price int64
PromoPrice int64
PromoDescription string
Partner1Price int64
Partner2Price int64
// Links Links
UpdatedAt time.Time
CreatedAt time.Time
view int
}
func (b Book1) MarshalJSON() (data []byte, err error) {
if b.view == 0 {
b.SetDefaultView()
}
switch b.view {
case SiteBook1View:
return json.Marshal(SiteBookView{
Id: b.Id,
Title: b.Title,
Description: b.Description,
Price: b.Price,
// Links: b.Links,
})
case Partner1Book1View:
return json.Marshal(Partner1BookView{
Id: b.Id,
Title: b.Title,
Partner1Price: b.Partner1Price,
// Links: b.Links,
})
case Partner2Book1View:
return json.Marshal(Partner2BookView{
Id: b.Id,
Partner2Title: b.Partner2Title,
Description: b.Description,
Partner2Price: b.Partner2Price,
// Links: b.Links,
})
case PromoBook1View:
return json.Marshal(PromoBookView{
Id: b.Id,
Title: b.Title,
Description: b.Description,
PromoPrice: b.PromoPrice,
PromoDescription: b.PromoDescription,
// Links: b.Links,
})
default:
err = fmt.Errorf("undefined view")
return
}
return
}
BenchmarkRun0-8 20000 68701 ns/op
BenchmarkRun1-8 200000 7177 ns/op
type Link struct {
Title string
Description string
Rate float64
}
type Links []Link
type Book struct {
Id int64
Title string
Description string
Partner2Title string
Price int64
PromoPrice int64
PromoDescription string
Partner1Price int64
Partner2Price int64
Links Links
UpdatedAt time.Time
CreatedAt time.Time
view BookView
}
type SiteBookView struct {
Id int64 `json:"sku"`
Title string `json:"title"`
Description string `json:"description"`
Price int64 `json:"price"`
Links Links `json:"links"`
}
//к остальным также добавим Links с каким-то json всевдонимом
Динамическое изменение схемы JSON в Go с помощью gob