LINUX.ORG.RU

Заполнить структуру в Golang

 


0

1

Доброго здравия всем!

Есть такая структура:

	type Bimbo struct {
		Messages []struct {
			Attachment struct {
				Type    string `json:"type"`
				Payload struct {
					TemplateType string `json:"template_type"`
					Text         string `json:"text"`
					Buttons      []struct {
						Type                string `json:"type"`
						URL                 string `json:"url"`
						Title               string `json:"title"`
						WebviewHeightRatio  string `json:"webview_height_ratio"`
						MessengerExtensions bool   `json:"messenger_extensions"`
					} `json:"buttons"`
				} `json:"payload"`
			} `json:"attachment"`
		} `json:"messages"`
	}

Как ее правильно заполнить? Если делать так:

input := new(Bimbo)
input.Messages[0].Attachment.Type = "sukaaa"

То получем закономерное - runtime error: index out of range

Что делать и как быть?

Спасибо!


Ответ на: комментарий от Abzu

А, точно, это ж тип без имени. Ну да, тогда я не пробовал как

vertexua ★★★★★
()

Начни с того, что разбей на отдельные типы и всё станет проще:

package main

import (
	"encoding/json"
	"log"
)

type Button struct {
	Type                string `json:"type,omitempty"`
	URL                 string `json:"url,omitempty"`
	Title               string `json:"title,omitempty"`
	WebviewHeightRatio  string `json:"webview_height_ratio,omitempty"`
	MessengerExtensions bool   `json:"messenger_extensions,omitempty"`
}

type Payload struct {
	TemplateType string   `json:"template_type,omitempty"`
	Text         string   `json:"text,omitempty"`
	Buttons      []Button `json:"buttons,omitempty"`
}

type Attachment struct {
	Type    string  `json:"type,omitempty"`
	Payload Payload `json:"payload"`
}

type Message struct {
	Attachment Attachment `json:"attachment"`
}

type Bimbo struct {
	Messages []Message `json:"messages,omitempty"`
}

func main() {
	input := Bimbo{
		Messages: []Message{
			Message{
				Attachment: Attachment{
					Type: "whatever",
				},
			},
		},
	}
	b, err := json.Marshal(input)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(b))
}
beastie ★★★★★
()

Всем спасибо!

Особенно beastie!

Abzu
() автор топика
Ответ на: комментарий от WitcherGeralt

Этим я пользовался, там и была эта структура сгенерина, а вот про галочку не заметил. Спасибо.

Abzu
() автор топика

Задроты не могут спасти мир

package main

import (
	"encoding/json"
	"fmt"
)

func main() {

	type Bimbo struct {
		Messages []struct {
			Attachment struct {
				Type    string `json:"type"`
				Payload struct {
					TemplateType string `json:"template_type"`
					Text         string `json:"text"`
					Buttons      []struct {
						Type                string `json:"type"`
						URL                 string `json:"url"`
						Title               string `json:"title"`
						WebviewHeightRatio  string `json:"webview_height_ratio"`
						MessengerExtensions bool   `json:"messenger_extensions"`
					} `json:"buttons"`
				} `json:"payload"`
			} `json:"attachment"`
		} `json:"messages"`
	}

	b := Bimbo{
		Messages: []struct {
			Attachment struct {
				Type    string `json:"type"`
				Payload struct {
					TemplateType string `json:"template_type"`
					Text         string `json:"text"`
					Buttons      []struct {
						Type                string `json:"type"`
						URL                 string `json:"url"`
						Title               string `json:"title"`
						WebviewHeightRatio  string `json:"webview_height_ratio"`
						MessengerExtensions bool   `json:"messenger_extensions"`
					} `json:"buttons"`
				} `json:"payload"`
			} `json:"attachment"`
		}{
			struct {
				Attachment struct {
					Type    string `json:"type"`
					Payload struct {
						TemplateType string `json:"template_type"`
						Text         string `json:"text"`
						Buttons      []struct {
							Type                string `json:"type"`
							URL                 string `json:"url"`
							Title               string `json:"title"`
							WebviewHeightRatio  string `json:"webview_height_ratio"`
							MessengerExtensions bool   `json:"messenger_extensions"`
						} `json:"buttons"`
					} `json:"payload"`
				} `json:"attachment"`
			}{
				Attachment: struct {
					Type    string `json:"type"`
					Payload struct {
						TemplateType string `json:"template_type"`
						Text         string `json:"text"`
						Buttons      []struct {
							Type                string `json:"type"`
							URL                 string `json:"url"`
							Title               string `json:"title"`
							WebviewHeightRatio  string `json:"webview_height_ratio"`
							MessengerExtensions bool   `json:"messenger_extensions"`
						} `json:"buttons"`
					} `json:"payload"`
				}{
					Type: "hard struct",
					Payload: struct {
						TemplateType string `json:"template_type"`
						Text         string `json:"text"`
						Buttons      []struct {
							Type                string `json:"type"`
							URL                 string `json:"url"`
							Title               string `json:"title"`
							WebviewHeightRatio  string `json:"webview_height_ratio"`
							MessengerExtensions bool   `json:"messenger_extensions"`
						} `json:"buttons"`
					}{
						TemplateType: "template",
						Text:         "text",
						Buttons: []struct {
							Type                string `json:"type"`
							URL                 string `json:"url"`
							Title               string `json:"title"`
							WebviewHeightRatio  string `json:"webview_height_ratio"`
							MessengerExtensions bool   `json:"messenger_extensions"`
						}{
							struct {
								Type                string `json:"type"`
								URL                 string `json:"url"`
								Title               string `json:"title"`
								WebviewHeightRatio  string `json:"webview_height_ratio"`
								MessengerExtensions bool   `json:"messenger_extensions"`
							}{
								Type:                "type",
								URL:                 "URL",
								Title:               "title",
								WebviewHeightRatio:  "string",
								MessengerExtensions: true,
							},
						},
					},
				},
			},
		},
	}

	fmt.Printf("it was not easy - %+v\n", b)

	bts, err := json.Marshal(&b)
	if err != nil {
		fmt.Printf("marshal to json err - %v\n", err)
	}
	fmt.Printf("b json - %s\n", string(bts))
}

DukeNukem
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.