Answer the question
In order to leave comments, you need to log in
What type of channel to put?
The task is to make a post request to the server, decode the response and send it to the channel. On the other hand, the goroutine pulls out of the channel and processes.
In general, I set the channel type, but I do not need to completely transfer events , a list element from it. The problem is that I don't know how to do it. Everything swears if I pass events.Events[0] which is not of the type that the channel needs.
Here is the code https://play.golang.org/p/SPp8wP1ZkEL
here is a screen that the server can send several updates, so you need to pull it out of the list
, you need to send not events but events.Events[0]
to the channel
and here is a screen of one of the element of that list ... in this one I need to transfer to the channel, and not completely, as above ...
Answer the question
In order to leave comments, you need to log in
It should be a little different, the first thing to change is the declaration of the structure itself, it should be like this
type Event struct {
EventID int `json:"eventId"`
Type string `json:"type"`
....
}
// канал создаёте вот так, т.к. вы хотите по одному событию передавать данные, а не целыми слайсами сразу
EventsCh = make(chan Event, 100)
go mailing(EventsCh)
// делаете HTTP запрос
response, responseErr := http.PostForm(...)
// создаёте decoder
decoder := json.NewDecoder(response.Body)
for {
event := Event{}
decoderErr := decoder.Decode(&event) // если данных нет - тут выполнение программы блокируется
if decodeErr != nil { // тут может быть ошибка io.EOF (просто данные закончились, сервер корректно закрыл соединение)
break
}
EventsCh <- event // отправляете данные в канал, из которого их читает горутина
}
func mailing(eventsCh chan Event){ //Получает события из канала
for{
event, ok := <- eventsChan
if !ok {
// канал закрыт
break
}
log.Print("Получено ", event)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question