Search code examples
gowebsocketstdoutstderrgorilla

How do you send websocket data after a page is rendered in Golang?



I am new to Golang and am trying to send data using web-sockets to a page. I have a handler and I want to be able to serve a file and after it is rendered send it a message. This is some code that I have now.

package main

import (
    "github.com/gorilla/websocket"
    "log"
    "fmt"
    "net/http"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func serveRoot(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "views/index.html")
    _, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }
}

func main() {
    http.HandleFunc("/", serveRoot)
    fmt.Println("Started")
    if err := http.ListenAndServe(":9090", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

The problem is that using the gorilla library I have no idea how to send data and I am getting some output when I load the page.

2018/01/23 08:35:24 http: multiple response.WriteHeader calls
2018/01/23 08:35:24 websocket: the client is not using the websocket protocol: 'upgrade' token not found in 'Connection' header
2018/01/23 08:35:24 http: multiple response.WriteHeader calls
2018/01/23 08:35:24 websocket: 'Origin' header value not allowed

Intention: Send some data after the page is rendered, then (later) hook it up to stdin/stderr
Disclaimer: I am just learning to code, so it would be a great help is you could take that into consideration and not be too vague.


Solution

  • So, as some of the comments mentioned, you can't upgrade a connection that has already been served html. The simple way to do this is just have one endpoint for your websockets, and one endpoint for your html.

    So in your example, you might do:

    http.HandleFunc("/", serveHtml) http.HandleFunc("/somethingElse", serveWebsocket)

    Where serveHtml has your http.ServeFile call, and serveWebsocket has the upgrading and wotnot.