M
M
Muxauko2020-05-12 17:29:39
go
Muxauko, 2020-05-12 17:29:39

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
5ebab2825c86b295222947.png

, 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 ...
5ebab2bf17fb9198465668.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-05-12
@Muxauko

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"`
        ....
}

Judging by the comment "//Making a longpoll request for updates" - the logic should be slightly different, you must make one request and then constantly decode (one at a time) the incoming data portions.
If I understood correctly, then you need to do it like this
// канал создаёте вот так, т.к. вы хотите по одному событию передавать данные, а не целыми слайсами сразу
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  // отправляете данные в канал, из которого их читает горутина
}

The mailing function should be like this
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 question

Ask a Question

731 491 924 answers to any question