V
V
Vladimir Grabko2016-05-21 21:06:47
JavaScript
Vladimir Grabko, 2016-05-21 21:06:47

Why is ws not working?

Can't connect to ws server. upgrade:websocket: origin not allowed
The server writes to the log

package main

import (
  "log"
  "net/http"

  "github.com/gorilla/websocket"
  "github.com/julienschmidt/httprouter"
)

func main() {
  router := httprouter.New()
  router.GET("/sdk/ws/", EventsWSHandler)
  //router.GET("/sdk/ajax/", EventsWSHandler)
  //router.GET("/sdk/jsonp/", EventsWSHandler)
  log.Fatal(http.ListenAndServe(":8080", router))

}

var upgrader = websocket.Upgrader{}

func EventsWSHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

  c, err := upgrader.Upgrade(w, r, nil)
  if err != nil {
    log.Print("upgrade:", err)
    return
  }
  defer c.Close()
  for {
    mt, message, err := c.ReadMessage()
    if err != nil {
      log.Println("read:", err)
      break
    }
    log.Printf("recv: %s", message)

    err = c.WriteMessage(mt, message)
    if err != nil {
      log.Println("write:", err)
      break
    }
  }
}

customer
var connection = new WebSocket('ws://localhost:8080/sdk/ws/');
                connection.onopen = function () {
                    console.log('Connection open!');

                    connection.send(JSON.stringify({
                        "event": "PageSkeleton",
                        "data": false
                    }));

                };
                connection.onclose = function () {
                    console.log('Connection closed');
                };
                connection.onerror = function (error) {
                    console.log('Error detected: ' + error);
                };
                connection.onmessage = function (e) {
                    var t = JSON.parse(e.data);
                    Events.Call(t["event"], t["data"])
                    console.log(t);
                };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Semchenko, 2016-05-21
@VGrabko

var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question