Skip to content
📞 A dead simple WebSocket connection written in Go.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples
.gitignore
.travis.yml
LICENSE
README.md
conn.go
conn_test.go
go.mod
go.sum
message.go
settings.go

README.md

websocket-conn Build Status

📞 A dead simple WebSocket connection written in Go.

websocket-conn provides you with easy handling for WebSockets, it's based on github.com/gorilla/websocket.

Installation

$ go get -u github.com/shiwano/websocket-conn

Usage

func Connect(ctx context.Context, settings Settings, url string, requestHeader http.Header) (*Conn *http.Response, error)
func UpgradeFromHTTP(ctx context.Context, settings Settings, w http.ResponseWriter, r *http.Request) (*Conn, error)

type Conn struct {
	Stream() <-chan Message
	Err() error
	SendBinaryMessage(data []byte) error
	SendTextMessage(text string) error
}

Examples

Server:

package main

import (
	"context"
	"net/http"
	"github.com/shiwano/websocket-conn"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		c, err := conn.UpgradeFromHTTP(ctx, conn.DefaultSettings(), w, r)
		if err != nil {
			w.Write([]byte("Error"))
			return
		}
		m := <-c.Stream()
		c.SendTextMessage(m.Text() + " World")
		cancel()
		for range c.Stream() {
		}
	})
	http.ListenAndServe(":5000", nil)
}

Client:

package main

import (
	"context"
	"log"
	"github.com/shiwano/websocket-conn"
)

func main() {
	c, _, err := conn.Connect(context.Background(), conn.DefaultSettings(), "ws://localhost:5000", nil)
	if err != nil {
		log.Fatal(err)
	}
	c.SendTextMessage("Hello")
	m := <-c.Stream()
	log.Println(m.Text()) // Hello World
	for range c.Stream() {
	}
}

See also examples directory.

License

Copyright (c) 2016 Shogo Iwano Licensed under the MIT license.

You can’t perform that action at this time.