forked from deven96/gosock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (72 loc) · 2.42 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
Simple Chat application using sockets in GoLang
*/
package main
import (
"flag"
"net/http"
"text/template"
"path/filepath"
"sync"
"github.com/deven96/gosock/pkg/custlog"
"github.com/gobuffalo/packr"
)
// declare global variables for use throughout the main package
// assets directory
var AssetsDir = filepath.Join("assets")
// command line arguments gotten from flag
// save logs to this file, defaults to "gosock.log"
var LogFile = flag.String("log", "gosock.log", "Name of the log file to save to")
// run web server at this address
var ServerLocation = flag.String("addr", ":8008", "The addr of the application.")
// templateHandler represents a single template
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
// ServeHTTP handles the HTTPRequest
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func(){
tmpdir := packr.NewBox("./templates")
custlog.Trace.Println("Created Packaging for templates")
// get the string of the html
htmlstr, _ := tmpdir.FindString(t.filename)
// create a new template instance to parse the htmlstr
parser := template.New("parser")
t.templ = template.Must(parser.Parse(htmlstr))
})
t.templ.Execute(w, r)
}
func main() {
flag.Parse() // parse the flags
defwriters := custlog.DefaultWriters(*LogFile, false)
//TRACE will be Discarded, while the rest will be routed accordingly
custlog.LogInit(defwriters)
custlog.Trace.Println("Imported Deven Custom Logging")
custlog.Info.Println("Log file can be found at ", custlog.Logfile)
//os.Setenv("GOSOCK_LOG", custlog.Logfile)
// create a room
r := newRoom()
//packers for packaging static files
//assets -> js, images
assetBox := packr.NewBox("./assets")
custlog.Trace.Printf("Creating Packaging for assets of type %T", assetBox)
//templates -> html
/* Routes */
// Handle function for route "/"
http.Handle("/chathandler", &templateHandler{filename: "chathandler.js"})
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(assetBox)))
http.Handle("/", &templateHandler{filename: "chat.html"})
// add everyone to the same room
http.Handle("/room", r)
//start the room
custlog.Info.Println("Initializing Room...")
go r.run()
//start the webserver
if err := http.ListenAndServe(*ServerLocation, nil); err != nil {
custlog.Error.Println(err)
}else{
custlog.Info.Printf("Running server started on %s", *ServerLocation)
}
}