send a json message to a tcp server in go

To send a JSON message to a TCP server in Go, you can follow the following steps:

  1. Establish a TCP connection to the server using the net package.
  2. Marshal your JSON message into bytes.
  3. Send the message bytes to the server using conn.Write() method.

Here's the sample code:

main.go
package main

import (
    "encoding/json"
    "fmt"
    "net"
)

type Message struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    // Establish TCP connection.
    conn, err := net.Dial("tcp", "localhost:8080")
    if err != nil {
        fmt.Println("Error connecting:", err.Error())
        return
    }
    defer conn.Close()

    msg := Message{"John Doe", 25}

    // Marshal message to JSON bytes.
    msgBytes, err := json.Marshal(msg)
    if err != nil {
        fmt.Println("Error marshaling:", err.Error())
        return
    }

    // Send bytes to server.
    _, err = conn.Write(msgBytes)
    if err != nil {
        fmt.Println("Error sending message:", err.Error())
    }

    fmt.Println("Message sent successfully!")
}
773 chars
40 lines

In the example above, we're defining a Message struct, which we're then marshaling into JSON bytes using the json.Marshal() method. We're then sending the bytes to the server using the conn.Write() method.

Note that you'll need to replace localhost:8080 with the actual address and port of your TCP server.

related categories

gistlibby LogSnag