101 lines
3.2 KiB
Go
101 lines
3.2 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"git.loafle.net/overflow/overflow_service_websocket/config"
|
|
"git.loafle.net/overflow/overflow_service_websocket/server"
|
|
"strings"
|
|
"github.com/golang/glog"
|
|
)
|
|
|
|
const (
|
|
version = "1.0.0"
|
|
website = "https://www.overflow.cloud"
|
|
banner = `
|
|
|
|
██████╗ ██╗ ██╗███████╗██████╗ ███████╗██╗ ██████╗ ██╗ ██╗
|
|
██╔═══██╗██║ ██║██╔════╝██╔══██╗██╔════╝██║ ██╔═══██╗██║ ██║
|
|
██║ ██║██║ ██║█████╗ ██████╔╝█████╗ ██║ ██║ ██║██║ █╗ ██║
|
|
██║ ██║╚██╗ ██╔╝██╔══╝ ██╔══██╗██╔══╝ ██║ ██║ ██║██║███╗██║
|
|
╚██████╔╝ ╚████╔╝ ███████╗██║ ██║██║ ███████╗╚██████╔╝╚███╔███╔╝
|
|
╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚══════╝ ╚═════╝ ╚══╝╚══╝
|
|
|
|
`
|
|
)
|
|
|
|
func printVersion() {
|
|
log.Printf("Version: %s\n", version)
|
|
log.Printf("Url: %s\n", website)
|
|
log.Println(banner)
|
|
}
|
|
|
|
func main() {
|
|
|
|
// Initialize config
|
|
config := loadConfig()
|
|
|
|
addr := config.Server.Addr
|
|
useTLS := config.Server.Tls
|
|
sConfig := server.NewOptions(&config.Websocket)
|
|
// Print banner
|
|
printVersion()
|
|
|
|
// Config TLS
|
|
|
|
ws := server.New(sConfig)
|
|
|
|
ws.OnConnection(func(c server.Client) {
|
|
log.Println("Client have been connected")
|
|
c.OnDisconnect(func(c server.Client) {
|
|
log.Println("Client have been disconnected")
|
|
})
|
|
})
|
|
|
|
http.Handle("/rpc", allowCORS(ws.HTTPHandler()))
|
|
log.Printf("Address: %s, UseTLS: %t", addr, useTLS)
|
|
|
|
if err := http.ListenAndServe(addr, nil); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
//https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/main.go
|
|
|
|
func allowCORS(h http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if origin := r.Header.Get("Origin"); origin != "" {
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
|
|
preflightHandler(w, r)
|
|
return
|
|
}
|
|
}
|
|
h.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func preflightHandler(w http.ResponseWriter, r *http.Request) {
|
|
headers := []string{"Content-Type", "Accept"}
|
|
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
|
|
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
|
|
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
|
|
glog.Infof("preflight request for %s", r.URL.Path)
|
|
return
|
|
}
|
|
|
|
func loadConfig() *config.Config {
|
|
os.Chdir("./")
|
|
wd, _ := os.Getwd()
|
|
path := filepath.Join(wd, "config.json")
|
|
|
|
err := config.InitConfig(path)
|
|
if nil != err {
|
|
log.Fatalln("Config error")
|
|
}
|
|
return config.GetConfig()
|
|
}
|