3
0
Fork 0
This repository has been archived on 2024-11-14. You can view files and clone it, but cannot push or open issues or pull requests.
ThemeParkPlus-Socket/server/websocket.go

52 lines
1.3 KiB
Go
Raw Normal View History

2022-08-12 19:08:47 +00:00
package server
import (
"github.com/Mindgamesnl/socketio"
"github.com/ParadoxPixel/ThemePark-Websocket/handlers"
"log"
"net/http"
"strings"
"time"
)
var runningServer *socketio.Server
type WrappedServer struct {
OriginalHandler http.Handler
}
func (wrapper WrappedServer) ServeHTTP(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Access-Control-Allow-Origin", "*")
res.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS")
res.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Origin")
if !strings.HasPrefix(req.URL.Path, "/socket.io/") {
_, _ = res.Write([]byte("{\"errors\":[{\"message\":\"something went wrong\",\"code\":\"BAD_REQUEST\"}],\"response\":{}}"))
return
}
wrapper.OriginalHandler.ServeHTTP(res, req)
}
func Start(namespace string, address string, debug bool) {
log.Println("Starting socket server")
server, _ := socketio.NewServer(time.Second*25, time.Second*5, socketio.DefaultParser)
runningServer = server
handlers.Load(server.Namespace(namespace), debug)
actualServer := CreateServer(address)
wrapper := WrappedServer{
OriginalHandler: server,
}
actualServer.Handler = wrapper
log.Println("Starting web server on ["+address+"]")
log.Fatal(actualServer.ListenAndServe())
}
func Stop() {
log.Println("Stopping web server")
_ = runningServer.Close()
}