I have a restful api. I integrate a route to opening a websocket when the user receives a new notification or message. Once socket is open, API doesn't work, it no longer receives any request.
this is my main func
func initWebSocket(){
http.HandleFunc("/websocket", websocketHandler)
}
func main() {
// init api's routes
initRoutes()
//init rethinkDB
api.InitRethinkDB()
//init opening websocket's route.
initWebSocket()
config := swagger.Config{
WebServices: restful.RegisteredWebServices(), // you control what services are visible
WebServicesUrl: "http://localhost:9000",
ApiPath: "/apidocs.json",
// Optionally, specifiy where the UI is located
SwaggerPath: "/apidocs/",
SwaggerFilePath: "swagger-ui/dist"}
swagger.InstallSwaggerService(config)
http.ListenAndServe(":9000", nil)
}
websocker handler :
func handleChangeNotification(socket *websocket.Conn, userID string, err chan string){
res, errr := r.Table("Notifications").
Filter(r.Row.Field("UserId").
Eq(userID)).
Changes().
Run(api.Sess)
var value HandleChange
if errr != nil {
err <- errr.Error()
}
for res.Next(&value){
var notif Notification
mapstructure.Decode(value.NewVal, ¬if)
errr := socket.WriteJSON(notif)
if errr != nil {
err <- errr.Error()
}
}
}
func websocketHandler(w http.ResponseWriter, r *http.Request){
socket, _ := upgrader.Upgrade(w, r, nil)
err := make(chan string)
run := false
go func(){
for {
if run == false {
go handleChangeNotification(socket, id, err)
run = true
}
if len(err) > 0 {
break
}
}
socket.Close()
}()
}
How can I do to run the websocket and API on the same server?