fyp/handler.go

322 lines
7.2 KiB
Go
Raw Normal View History

2023-09-18 00:26:42 +01:00
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func baseLoadTemplate(base string, path string) (*template.Template, any) {
return template.New(base).ParseFiles(
"./views/"+base,
"./views/"+path,
"./views/partials/header.html",
)
}
func loadTemplate(path string) (*template.Template, any) {
return baseLoadTemplate("layout.html", path)
}
func LoadView(writer http.ResponseWriter, path string, data interface{}) {
tmpl, err := loadTemplate(path)
if err != nil {
fmt.Printf("Failed to load view %s\n", path)
fmt.Println(err)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadView(writer, "500.html", nil)
}
return
}
if err := tmpl.Execute(writer, data); err != nil {
fmt.Printf("Failed to load view %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadView(writer, "500.html", nil)
}
return
}
}
/** Only returns the html without template */
func LoadHtml(writer http.ResponseWriter, path string, data interface{}) {
tmpl, err := baseLoadTemplate("html.html", path)
if err != nil {
fmt.Printf("Failed to load template %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadHtml(writer, "500.html", nil)
}
return
}
if err := tmpl.Execute(writer, data); err != nil {
fmt.Printf("Failed to execute template %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadHtml(writer, "500.html", nil)
}
return
}
}
type Error struct {
code int
msg *string
}
type AnswerType int
const (
NORMAL AnswerType = 1 << iota
2023-09-18 00:26:42 +01:00
HTML
JSON
HTMLFULL
)
func LoadBasedOnAnswer(ans AnswerType, w http.ResponseWriter, path string, data map[string]interface{}) {
if ans == NORMAL {
LoadView(w, path, nil)
return
} else if ans == HTML {
LoadHtml(w, path, nil)
return
} else if ans == HTMLFULL {
if data == nil {
LoadHtml(w, path, map[string]interface{}{
"App": true,
})
} else {
data["App"] = true
LoadHtml(w, path, data)
}
return
} else if ans == JSON {
panic("TODO JSON!")
} else {
panic("unreachable")
}
}
type HandleFunc struct {
path string
mode AnswerType
fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error
}
2023-09-18 00:26:42 +01:00
type Handler interface {
New()
Startup()
Get(fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error)
Post(fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error)
2023-09-18 00:26:42 +01:00
}
type Handle struct {
gets []HandleFunc
posts []HandleFunc
}
2023-09-18 00:26:42 +01:00
func handleError(err *Error, answerType AnswerType, w http.ResponseWriter) {
if err != nil {
w.WriteHeader(err.code)
if err.code == 404 {
LoadBasedOnAnswer(answerType, w, "404.html", nil)
2023-09-18 00:26:42 +01:00
return
}
if err.msg != nil {
w.Write([]byte(*err.msg))
}
}
}
func (x *Handle) Get(path string, fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL | JSON,
2023-09-18 00:26:42 +01:00
}
x.gets = append(x.gets, nhandler)
}
func (x *Handle) GetHTML(path string, fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL,
2023-09-18 00:26:42 +01:00
}
x.gets = append(x.gets, nhandler)
}
func (x *Handle) GetJSON(path string, fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: JSON,
2023-09-18 00:26:42 +01:00
}
x.gets = append(x.gets, nhandler)
}
func (x *Handle) Post(path string, fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL | JSON,
}
x.posts = append(x.posts, nhandler)
2023-09-18 00:26:42 +01:00
}
func (x *Handle) PostHTML(path string, fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL,
}
x.posts = append(x.posts, nhandler)
}
func (x *Handle) PostJSON(path string, fn func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: JSON,
}
x.posts = append(x.posts, nhandler)
}
func (x *Handle) handleGets(ans AnswerType, w http.ResponseWriter, r *http.Request) {
for _, s := range x.gets {
fmt.Printf("target: %s, paths: %s\n", s.path, r.URL.Path)
if s.path == r.URL.Path && ans&s.mode != 0 {
s.fn(ans, w, r)
return
}
}
w.WriteHeader(http.StatusNotFound)
LoadBasedOnAnswer(ans, w, "404.html", nil)
}
func (x *Handle) handlePosts(ans AnswerType, w http.ResponseWriter, r *http.Request) {
for _, s := range x.posts {
if s.path == r.URL.Path && ans&s.mode != 0 {
s.fn(ans, w, r)
return
}
}
w.WriteHeader(http.StatusNotFound)
LoadBasedOnAnswer(ans, w, "404.html", nil)
}
func AnswerTemplate(path string, data interface{}) func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error {
return func(mode AnswerType, w http.ResponseWriter, r *http.Request) *Error {
LoadBasedOnAnswer(mode, w, path, nil)
return nil
}
}
func NewHandler() *Handle {
x := &Handle{}
2023-09-18 00:26:42 +01:00
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ans := NORMAL
if r.Header.Get("Request-Type") == "htmlfull" {
ans = HTMLFULL
}
if r.Header.Get("Request-Type") == "html" {
ans = HTML
}
//TODO JSON
if r.Method == "GET" {
x.handleGets(ans, w, r)
2023-09-18 00:26:42 +01:00
return
}
if r.Method == "POST" {
x.handlePosts(ans, w, r)
return
}
panic("TODO handle: " + r.Method)
2023-09-18 00:26:42 +01:00
})
// TODO Handle this in other way
2023-09-18 00:26:42 +01:00
http.HandleFunc("/styles/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[len("/styles/"):]
if !strings.HasSuffix(path, ".css") {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("File not found"))
return
}
t, err := template.ParseFiles("./views/styles/" + path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to load template"))
fmt.Println("Error:")
fmt.Println(err)
return
}
w.Header().Set("Content-Type", "text/css; charset=utf-8")
t.Execute(w, nil)
})
// TODO Handle this in other way
http.HandleFunc("/js/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[len("/js/"):]
if !strings.HasSuffix(path, ".js") {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("File not found"))
return
}
t, err := template.ParseFiles("./views/js/" + path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to load template"))
fmt.Println("Error:")
fmt.Println(err)
return
}
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
t.Execute(w, nil)
})
return x
2023-09-18 00:26:42 +01:00
}
func (x Handle) Startup() {
fmt.Printf("Starting up!\n")
log.Fatal(http.ListenAndServe(":8000", nil))
}