socket icon indicating copy to clipboard operation
socket copied to clipboard

Simple Socket.io alternative with #golang server

socket

GoDoc Software License

Simple Socket.io alternative with #golang server

Usage

Server:

package main

import (
  "fmt"
  "net/http"

  "github.com/djherbis/socket"
)

type MyObject struct{
  Text string `json:"text"`
}

func main() {
  server := socket.NewServer()

  server.On(socket.Connection, func(so socket.Socket) {
    so.Emit("hello", "world")

    so.On("hey", func(msg string) {
      fmt.Println(msg)
    })

    so.On("new obj", func(myobj MyObject){
      fmt.Println(myobj)
    })

    so.Emit("server obj", MyObject{Text: "obj from server to client"})
  })

  router := http.NewServeMux()
  router.Handle("/socket", server)
  router.Handle("/", http.FileServer(http.Dir("."))) // serve up socket.js
  http.ListenAndServe("localhost:8080", router)
}

Client:

<script src="socket.js"></script>
<script>
  var socket = io("localhost:8080/");
  
  socket.emit("hey", "hey there!");
  
  socket.on("hello", function(msg){
    console.log(msg);
  });
  
  socket.emit("new obj", {text: "objects are automatically marshalled/unmarshalled"});

  socket.on("server obj", function(myobj){
    console.log(myobj);
  });
</script>

Installation

# Server Side
go get github.com/djherbis/socket

# Client Side
<script src="socket.js"></script>