receive a json message from a channel in go

To receive a JSON message from a channel in Go, you first need to define the JSON message structure. Let's consider an example JSON message with the following structure:

main.go
{
    "name": "Alice",
    "age": 25,
    "address": {
        "city": "New York",
        "state": "NY"
    }
}
113 chars
9 lines

To receive this message from a channel, you can define a struct that matches the structure of the JSON message:

main.go
type Person struct {
    Name    string
    Age     int
    Address struct {
        City  string
        State string
    }
}
127 chars
9 lines

Then, you can create a channel of type Person and start a goroutine that listens to the channel and processes the incoming JSON messages:

main.go
personChan := make(chan Person)

go func() {
    for person := range personChan {
        // process the incoming JSON message
        fmt.Println(person.Name, "is", person.Age, "years old and lives in", person.Address.City, ",", person.Address.State)
    }
}()
262 chars
9 lines

Finally, to send a JSON message to the channel, you can use the json.Unmarshal function to convert the message from a byte slice to a Person struct, and then send the struct over the channel:

main.go
jsonMsg := []byte(`{
    "name": "Alice",
    "age": 25,
    "address": {
        "city": "New York",
        "state": "NY"
    }
}`)

var person Person
err := json.Unmarshal(jsonMsg, &person)
if err != nil {
    // handle error
}

personChan <- person
253 chars
17 lines

The goroutine listening to the channel will receive the message and process it accordingly.

related categories

gistlibby LogSnag