send a json message to a udp server in go

To send a JSON message to a UDP server in Go, follow these steps:

  1. Define your JSON message as a struct type:
main.go
type Message struct {
    Field1 string `json:"field1"`
    Field2 int `json:"field2"`
    // add more fields as needed
}
122 chars
6 lines
  1. Marshal your message to JSON:
main.go
msg := Message{"hello", 123}
jsonBytes, err := json.Marshal(msg)
if err != nil {
    // handle error
}
103 chars
6 lines
  1. Resolve the UDP address of the server:
main.go
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:1234")
if err != nil {
    // handle error
}
98 chars
5 lines
  1. Create a UDP connection:
main.go
conn, err := net.DialUDP("udp", nil, udpAddr)
if err != nil {
    // handle error
}
defer conn.Close()
103 chars
6 lines
  1. Send the JSON message over the connection:
main.go
_, err = conn.Write(jsonBytes)
if err != nil {
    // handle error
}
69 chars
5 lines

Here's the complete example:

main.go
package main

import (
    "encoding/json"
    "net"
)

type Message struct {
    Field1 string `json:"field1"`
    Field2 int `json:"field2"`
}

func main() {
    msg := Message{"hello", 123}
    jsonBytes, err := json.Marshal(msg)
    if err != nil {
        panic(err)
    }

    udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:1234")
    if err != nil {
        panic(err)
    }

    conn, err := net.DialUDP("udp", nil, udpAddr)
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    _, err = conn.Write(jsonBytes)
    if err != nil {
        panic(err)
    }
}
590 chars
36 lines

related categories

gistlibby LogSnag