about summary refs log tree commit diff
path: root/src/http.go
blob: 9690db63fbd7ef6b35276c6fe529205a820a3581 (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
56
57
58
59
60
package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
)

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["version"] = os.Getenv("VERSION")
		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(fmt.Sprintf("%s/*.html", templatesPath))
		if err != nil {
			log.Printf("Error reading the template Path: %s/*.html", templatesPath)
			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)
	}
}