Как создать json из slice в go

У меня есть такая модель с хардкордным методом All

package product

type Product struct {
    ID          int    `json:"id"`
    Name        string `json:"name"`
    Slug        string `json:"slug"`
    Description string `json:"description"`
}

func (p Product) All() []Product {

    return []Product{
        {ID: 1, Name: "World of Authcraft", Slug: "world-of-authcraft", Description: "Battle bugs and protect yourself from invaders while you explore a scary world with no security"},
        {ID: 2, Name: "Ocean Explorer", Slug: "ocean-explorer", Description: "Explore the depths of the sea in this one of a kind underwater experience"},
        {ID: 3, Name: "Dinosaur Park", Slug: "dinosaur-park", Description: "Go back 65 million years in the past and ride a T-Rex"},
        {ID: 4, Name: "Cars VR", Slug: "cars-vr", Description: "Get behind the wheel of the fastest cars in the world."},
        {ID: 5, Name: "Robin Hood", Slug: "robin-hood", Description: "Pick up the bow and arrow and master the art of archery"},
        {ID: 6, Name: "Real World VR", Slug: "real-world-vr", Description: "Explore the seven wonders of the world in VR"}}

}

И вот такой обработчик

func toJSON(data interface{}) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println(data)
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(data)
    })
}

Принт выдает почему то шестнадцатеричное число 0x684180

Как нужно обрабатывать правильно чтобы получить json?


Ответы (1 шт):

Автор решения: prospero78su

Может быть в конце ваш байтовый срез надо преобразовать в строку (прежде чем в браузер отдать, ведь HTTP -- это текстовый протокол)? Зачем вам новый объект кодировщика JSON? Вызов простой функции Marshall() из того же пакета уже не модно?

→ Ссылка