-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
86 lines (72 loc) · 1.91 KB
/
utils.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
package main
import (
"errors"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"github.com/sausheong/Chapter_2_Go_ChitChat/chitchat/data"
"github.com/sirupsen/logrus"
)
type Configuration struct {
Address string
ReadTimeout int64
WriteTimeout int64
Static string
}
var config Configuration
var logger *log.Logger
// Convenience function for printing to stdout
func p(a ...interface{}) {
logrus.Info(a)
}
// Convenience function to redirect to the error message page
func error_message(writer http.ResponseWriter, request *http.Request, msg string) {
url := []string{"/err?msg=", msg}
http.Redirect(writer, request, strings.Join(url, ""), 302)
}
// Checks if the user is logged in and has a session, if not err is not nil
func session(writer http.ResponseWriter, request *http.Request) (sess data.Session, err error) {
cookie, err := request.Cookie("_cookie")
if err == nil {
sess = data.Session{Uuid: cookie.Value}
if ok, _ := sess.Check(); !ok {
err = errors.New("Invalid session")
}
}
return
}
// parse HTML templates
// pass in a list of file names, and get a template
func parseTemplateFiles(filenames ...string) (t *template.Template) {
var files []string
t = template.New("layout")
for _, file := range filenames {
files = append(files, fmt.Sprintf("templates/%s.html", file))
}
t = template.Must(t.ParseFiles(files...))
return
}
func generateHTML(writer http.ResponseWriter, data interface{}, filenames ...string) {
var files []string
for _, file := range filenames {
files = append(files, fmt.Sprintf("templates/%s.html", file))
}
templates := template.Must(template.ParseFiles(files...))
templates.ExecuteTemplate(writer, "layout", data)
}
// for logging
func info(args ...interface{}) {
logrus.Info(args)
}
func danger(args ...interface{}) {
logrus.Error(args)
}
func warning(args ...interface{}) {
logrus.Warn(args)
}
// version
func version() string {
return "0.1"
}