'Golang WebSocket connection

I started learning Golang. And I have this project, where I need to stream some data from API via WebSocket connection, and print it in the console.

And the thing I don't understand - I have a URL, so I can make a request on it (through net/http package), but how can I upgrade it to WebSocket?

Can I make it only using pure Golang? I couldn't find appropriate information on the internet. All examples use JS, or they make it too complicated (like building some app, which I don't want to, and simply can't follow along, because of its complexity).



Solution 1:[1]

I got you. WebSocket has client side and server side. Most of the time people need run client side in browser. gorilla's websocket implementation supports both client and server. you can use it to dial your server. here is an example code.

package main

import (
    "fmt"
    "github.com/gorilla/websocket"
)

func main() {
    ws, _, err := websocket.DefaultDialer.Dial("ws[s]://localhost/path?query", nil)
    if err != nil {
        panic(err)
    }
    defer ws.Close()

    for {
        // Read a message from websocket connection
        _, msg, err := ws.ReadMessage()
        if err != nil {
             return
        }

        fmt.Println(string(msg))

        // uncomment below if you need send message to remote server
        //if err = ws.WriteMessage(websocket.TextMessage, msg); err != nil {
        //  return
        //}
    }
}

Here is the completed simple client and server example: https://github.com/gorilla/websocket/tree/master/examples/echo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chengbin du