go: create base websocket server

master
ALI Hamza 2019-10-12 21:07:40 +07:00
parent e181a09b4b
commit 09073ac4ff
No known key found for this signature in database
GPG Key ID: 7C608266BF384ADC
5 changed files with 70 additions and 1 deletions

@ -4,5 +4,7 @@ go 1.13
require (
github.com/bwmarrin/discordgo v0.19.0
github.com/gorilla/mux v1.7.3 // indirect
github.com/gorilla/websocket v1.4.1
github.com/mattn/go-sqlite3 v1.11.0
)

@ -1,7 +1,11 @@
github.com/bwmarrin/discordgo v0.19.0 h1:kMED/DB0NR1QhRcalb85w0Cu3Ep2OrGAqZH1R5awQiY=
github.com/bwmarrin/discordgo v0.19.0/go.mod h1:O9S4p+ofTFwB02em7jkpkV8M3R0/PUVOwN61zSZ0r4Q=
github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/mattn/go-sqlite3 v1.11.0 h1:LDdKkqtYlom37fkvqs8rMPFKAMe8+SgjbwZ6ex1/A/Q=
github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16 h1:y6ce7gCWtnH+m3dCjzQ1PCuwl28DDIc3VNnvY29DlIA=

@ -1,6 +1,7 @@
package main
import (
"TerraOceanBot/server"
"io/ioutil"
"sync"
@ -10,7 +11,7 @@ import (
func main() {
token, _ := ioutil.ReadFile("token.txt")
wg := sync.WaitGroup{}
wg.Add(1)
go discord.StartBot(string(token), &wg)
server.StartServer(8080, &wg)
wg.Wait()
}

@ -0,0 +1,17 @@
package server
import "github.com/gorilla/websocket"
var clients = make(map[*websocket.Conn]bool)
func newSession(who *websocket.Conn) {
clients[who] = true
}
func disconnectSession(who *websocket.Conn) {
delete(clients, who)
}
func handleIncomingMessage(who *websocket.Conn, msg string) {
//TODO
}

@ -0,0 +1,45 @@
package server
import (
"fmt"
"log"
"net/http"
"strconv"
"sync"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func newConnection(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Fprint(w, "You must use the websocket protocol to connect to this endpoint.", err)
}
defer ws.Close()
newSession(ws)
for {
_, p, err := ws.ReadMessage()
if err != nil {
disconnectSession(ws)
break
}
msg := string(p)
handleIncomingMessage(ws, msg)
}
}
func StartServer(port int, wg *sync.WaitGroup) {
defer wg.Done()
hostLocation := ":" + strconv.Itoa(port)
http.HandleFunc("/ws", newConnection)
log.Fatal(http.ListenAndServe(hostLocation, nil))
}