go: Replace wait group with channel

master
Luther Wen Xu 2019-10-12 23:49:28 +07:00
parent 38580f8910
commit 32ae99c225
Signed by untrusted user: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
3 changed files with 22 additions and 18 deletions

@ -2,19 +2,14 @@ package discord
import (
"fmt"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"github.com/bwmarrin/discordgo"
"TerraOceanBot/discord/modules"
)
func StartBot(token string, wg *sync.WaitGroup) {
defer wg.Done()
func StartBot(token string, kill chan bool) {
dg, err := discordgo.New("Bot " + strings.TrimSpace(token))
if err != nil {
panic(err)
@ -32,10 +27,11 @@ func StartBot(token string, wg *sync.WaitGroup) {
fmt.Println("Bot is now running. Press CTRL-C to exit.")
go modules.ListenToVoteFinishes(dg)
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
<-kill
dg.Close()
fmt.Println("Discordgo exited successfully.")
<-kill
}

@ -3,15 +3,26 @@ package main
import (
"TerraOceanBot/server"
"io/ioutil"
"sync"
"os"
"os/signal"
"syscall"
"TerraOceanBot/discord"
)
func main() {
token, _ := ioutil.ReadFile("token.txt")
wg := sync.WaitGroup{}
go discord.StartBot(string(token), &wg)
server.StartServer(8080, &wg)
wg.Wait()
endGracefully := make(chan bool)
go discord.StartBot(string(token), endGracefully)
go server.StartServer(8080)
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
//Notification to end
endGracefully <- true
//Wait for it to actually end
endGracefully <- true
}

@ -5,7 +5,6 @@ import (
"log"
"net/http"
"strconv"
"sync"
"github.com/gorilla/websocket"
)
@ -35,9 +34,7 @@ func newConnection(w http.ResponseWriter, r *http.Request) {
}
}
func StartServer(port int, wg *sync.WaitGroup) {
defer wg.Done()
func StartServer(port int) {
hostLocation := ":" + strconv.Itoa(port)
http.HandleFunc("/ws", newConnection)