Golang : Web(Javascript) to server-side websocket example
For this tutorial, we will explore how to write a HTML page with Javascript/JQuery that interface with server-side Golang service via Websocket. Also, this tutorial demonstrates the alternative way of posting data(apart from AJAX) to server-side and getting reply. (see also https://www.socketloop.com/tutorials/golang-jquery-ajax-post-data-to-server-and-send-data-back-to-client-example )
In the past, many gaming, chat, stock ticker or multi-user applications abused the HTTP protocol to poll the server for updates and at the same time upload notifications data back to the server as distinct HTTP calls. There are several problems that were encountered with this method. One of it is that the client-side is forced to maintain a mapping from the outgoing connections to the incoming connection to track replies.
To mitigate this problem without reinventing the entire HTTP protocol, Websocket is created as a simpler solution that enable applications to have bidirectional communication with server-side services in real time and works on port 80(http) and 443(https).
Here we go!
package main
import (
"fmt"
"github.com/gorilla/mux"
"golang.org/x/net/websocket"
"io"
"net/http"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
html := `<!DOCTYPE html>
<html>
<head>
<title>Javascript/JQuery/Golang and Websocket example</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function() {
var ws = new WebSocket("ws://example.com:8080/reply"); // change example.com
var $ul = $('#msg-list');
$('#sendBtn').click(function(){
var data = $('#name').val();
ws.send(data);
console.log("Sending data to server via Webscoket :" + data);
$('<li>').text(data).appendTo($ul);
});
});
</script>
</head>
<body>
<input id="name" type="text" />
<input type="button" id="sendBtn" value="send"></input>
<ul id="msg-list"></ul>
</body></html>`
w.Write([]byte(fmt.Sprintf(html)))
}
func replyHandler(ws *websocket.Conn) {
io.Copy(ws, ws)
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", homeHandler)
// convert to Handler, otherwise compiler will report
// error : cannot use websocket.Handler(replyHandler) (type websocket.Handler)
mx.Handle("/reply", websocket.Handler(replyHandler))
http.ListenAndServe(":8080", mx)
}
NOTE : Do consider websocket protocol into your microservice architecture.
NOTE : The code example here is adapted from https://github.com/golang-samples/websocket/blob/master/simple/main.go
References :
See also : Golang : JQuery AJAX post data to server and send data back to client example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.4k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+19.1k Golang : Get current URL example
+20.1k Golang : Pipe output from one os.Exec(shell command) to another command
+12.2k Golang : Add ASCII art to command line application launching process
+12.7k Golang : Handle or parse date string with Z suffix(RFC3339) example
+11.6k Golang : Convert decimal number(integer) to IPv4 address
+19.4k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+5.3k Golang : Frobnicate or tweaking a string example
+7k Golang : Calculate how many weeks left to go in a given year
+4.7k Linux : How to set root password in Linux Mint
+17k Golang : Multi threading or run two processes or more example
+9.4k Golang : List available AWS regions