Go WebSocket

Publish with Go-lang

How to subscribe? see here

Use the following code snippet to publish a message/event on a WebSocket Channel Room with Go.

package main
import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {
  url := "https://CLUSTER_ID.piesocket.com/api/publish"
  method := "POST"

  //Demo secret and key, get yours at piesocket.com
  payload := strings.NewReader("{\n    \"key\": \"oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm\",\n    \"secret\": \"d8129f82f8dd71910aa4a7efa30a7297\",\n    \"roomId\": 1,\n    \"message\": \"Hello world!\"\n}")

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
  }
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  defer res.Body.Close()
  body, err := ioutil.ReadAll(res.Body)

  fmt.Println(string(body))
}

Copy

This sends a string message to Room 1.

To send an Event, use following message payload

{"event":"new-message","data":"Hello"}

Copy

Please note that this example uses a demo key and secret, which is public. The demo key is only for quick testing purposes, and you should not use this in your application.

You can get your free API key and API secret here.

Help

Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.