The JSON object

It is expected that many websocket clients and servers will exchange data in JSON format. For Go programs this means that a Go object will be marshalled into JSON format as described in Chapter 4: Serialisation and then sent as a UTF-8 string, while the receiver will read this string and unmarshal it back into a Go object.

The websocket convenience object JSON will do this for you. It has methods Send and Receive for sending and receiving data, just like the Message object.

A client that sends a Person object in JSON format is

  1. /* PersonClientJSON
  2. */
  3. package main
  4. import (
  5. "golang.org/x/net/websocket"
  6. "fmt"
  7. "os"
  8. )
  9. type Person struct {
  10. Name string
  11. Emails []string
  12. }
  13. func main() {
  14. if len(os.Args) != 2 {
  15. fmt.Println("Usage: ", os.Args[0], "ws://host:port")
  16. os.Exit(1)
  17. }
  18. service := os.Args[1]
  19. conn, err := websocket.Dial(service, "",
  20. "http://localhost")
  21. checkError(err)
  22. person := Person{Name: "Jan",
  23. Emails: []string{"ja@newmarch.name", "jan.newmarch@gmail.com"},
  24. }
  25. err = websocket.JSON.Send(conn, person)
  26. if err != nil {
  27. fmt.Println("Couldn't send msg " + err.Error())
  28. }
  29. os.Exit(0)
  30. }
  31. func checkError(err error) {
  32. if err != nil {
  33. fmt.Println("Fatal error ", err.Error())
  34. os.Exit(1)
  35. }
  36. }

and a server that reads it is

  1. /* PersonServerJSON
  2. */
  3. package main
  4. import (
  5. "golang.org/x/net/websocket"
  6. "fmt"
  7. "net/http"
  8. "os"
  9. )
  10. type Person struct {
  11. Name string
  12. Emails []string
  13. }
  14. func ReceivePerson(ws *websocket.Conn) {
  15. var person Person
  16. err := websocket.JSON.Receive(ws, &person)
  17. if err != nil {
  18. fmt.Println("Can't receive")
  19. } else {
  20. fmt.Println("Name: " + person.Name)
  21. for _, e := range person.Emails {
  22. fmt.Println("An email: " + e)
  23. }
  24. }
  25. }
  26. func main() {
  27. http.Handle("/", websocket.Handler(ReceivePerson))
  28. err := http.ListenAndServe(":12345", nil)
  29. checkError(err)
  30. }
  31. func checkError(err error) {
  32. if err != nil {
  33. fmt.Println("Fatal error ", err.Error())
  34. os.Exit(1)
  35. }
  36. }