Question

I am trying to implement a simple "global" counter that updates based on every user that clicks the button on their browsers button. For example, if you go to the website and click the button, I will see the counter increase on my side if I'm on the same website. I sought to do this with long polling, but am facing some issues. Mainly the server variable is not coming back as I think it should.

The server:

package main

import (
    "net/http"
    "log"
    "io"
    "io/ioutil"
)

var messages chan string = make(chan string, 100)

var counter = 0

func PushHandler(w http.ResponseWriter, req *http.Request) {

    body, err := ioutil.ReadAll(req.Body)

    if err != nil {
        w.WriteHeader(400)
    }
    counter += 1
    messages <- string(counter)
}


func PollResponse(w http.ResponseWriter, req *http.Request) {

    io.WriteString(w, <-messages)
}

func main() {
    http.Handle("/", http.FileServer(http.Dir("./")))
    http.HandleFunc("/poll", PollResponse)
    http.HandleFunc("/push", PushHandler)
    err := http.ListenAndServe(":8005", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

The client:

<html>
<script language=javascript>

function longpoll(url, callback) {

    var req = new XMLHttpRequest (); 
    req.open ('GET', url, true); 

    req.onreadystatechange = function (aEvt) {
        if (req.readyState == 4) { 
            if (req.status == 200) {
                callback(req.responseText);
                longpoll(url, callback);
            } else {
                alert ("long-poll connection lost");
            }
        }
    };

    req.send(null);
}

function recv(msg) {

    var box = document.getElementById("counter");

    box.value += msg + "\n";
}
function send() {


    var box = document.getElementById("counter");

  var req = new XMLHttpRequest (); 
    req.open ('POST', "/push?rcpt=", true); 

    req.onreadystatechange = function (aEvt) {
        if (req.readyState == 4) { 
            if (req.status == 200) {
            } else {
                alert ("failed to send!");
            }
        }
  };
  req.send("hi")

  //box.innerHTML += "test" ;  
}
</script>
<body onload="longpoll('/poll', recv);">

<h1> Long-Poll Chat Demo </h1>

<p id="counter"></p>
<button onclick="send()" id="test">Test Button</button>
</body>
</html>

The counter variable is not coming back from the server for some reason. I believe I am changing the state every time the button is clicked and so the longpolling function should get the newly updated counter variable. If you have any suggestions, please let me know!

Was it helpful?

Solution

I see two issues in you program: 1. In the server:

messages <- string(counter)

You should use "strconv" package

messages <- strconv.Itoa(counter)

string(0) will return something like []byte{0} not a "0"
2. In your client:

function recv(msg) {
    var box = document.getElementById("counter");
    box.value += msg + "\n";
}

Should be:

function recv(msg) {
    var box = document.getElementById("counter");
    box.innerHTML += msg + "\n";
}

I don't think the p element have value property

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top