about summary refs log tree commit diff
path: root/src/http.go
blob: 894542a52bf675d40d473352e7aff7dfed304c94 (plain)
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
package main

import (
	"html/template"
	"net/http"
)

type Link struct {
	Name   string
	Target string
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		// define data
		data := map[string]interface{}{}
		data["pagelink1"] = ""
		data["pagelinknext"] = []Link{
			{Name: "user/", Target: "/user"},
			{Name: "bot/", Target: "/bot"},
			{Name: "battle/", Target: "/battle"},
		}
		data["pagelinkauth"] = []Link{
			{Name: "login/", Target: "/login"},
			{Name: "register/", Target: "/register"},
		}

		session, _ := globalState.sessions.Get(r, "session")
		username := session.Values["username"]

		if username != nil {
			data["logged_in"] = true

			user, err := UserGetUserFromUsername(username.(string))
			if err != nil {
				data["err"] = "Couln't get the user"
			}
			data["user"] = user
		}

		// get the template
		t, err := template.ParseGlob("./templates/*.html")
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Error reading template file"))
			return
		}

		// exec!
		t.ExecuteTemplate(w, "index", data)
	default:
		http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
	}
}