This commit is contained in:
2023-10-20 12:37:56 +01:00
parent b5ba0d295a
commit bc801648a3
6 changed files with 182 additions and 131 deletions

View File

@@ -13,24 +13,24 @@ import (
"time"
dbtypes "git.andr3h3nriqu3s.com/andr3/fyp/logic/db_types"
"github.com/charmbracelet/log"
"github.com/charmbracelet/log"
)
func Mul (n1 int, n2 int) int {
return n1 * n2
func Mul(n1 int, n2 int) int {
return n1 * n2
}
func Add (n1 int, n2 int) int {
return n1 + n2
func Add(n1 int, n2 int) int {
return n1 + n2
}
func baseLoadTemplate(base string, path string) (*template.Template, any) {
funcs := map[string]any {
"startsWith": strings.HasPrefix,
"replace": strings.Replace,
"mul": Mul,
"add": Add,
}
funcs := map[string]any{
"startsWith": strings.HasPrefix,
"replace": strings.Replace,
"mul": Mul,
"add": Add,
}
return template.New(base).Funcs(funcs).ParseFiles(
"./views/"+base,
"./views/"+path,
@@ -97,27 +97,27 @@ func LoadHtml(writer http.ResponseWriter, path string, data interface{}) {
}
func LoadDefineTemplate(writer http.ResponseWriter, path string, base string, data AnyMap) {
if data == nil {
data = map[string]interface{} {
"Error": true,
}
} else {
data["Error"] = true
}
if data == nil {
data = map[string]interface{}{
"Error": true,
}
} else {
data["Error"] = true
}
funcs := map[string]any {
"startsWith": strings.HasPrefix,
"mul": Mul,
"replace": strings.Replace,
"add": Add,
}
funcs := map[string]any{
"startsWith": strings.HasPrefix,
"mul": Mul,
"replace": strings.Replace,
"add": Add,
}
tmpl, err := template.New("").Funcs(funcs).Parse("{{template \"" + base + "\" . }}")
if err != nil {
panic("Lol")
}
if err != nil {
panic("Lol")
}
tmpl, err = tmpl.ParseFiles(
tmpl, err = tmpl.ParseFiles(
"./views/"+path,
"./views/partials/header.html",
)
@@ -222,10 +222,10 @@ func handleError(err *Error, w http.ResponseWriter, context *Context) {
if err != nil {
data := context.AddMap(err.data)
if err.Code == http.StatusNotFound {
if context.Mode == HTML {
w.WriteHeader(309)
context.Mode = HTMLFULL
}
if context.Mode == HTML {
w.WriteHeader(309)
context.Mode = HTMLFULL
}
LoadBasedOnAnswer(context.Mode, w, "404.html", data)
return
}
@@ -340,46 +340,46 @@ func AnswerTemplate(path string, data AnyMap, authLevel int) func(w http.Respons
}
type Context struct {
Token *string
User *dbtypes.User
Mode AnswerType
Logger *log.Logger
Db *sql.DB
Token *string
User *dbtypes.User
Mode AnswerType
Logger *log.Logger
Db *sql.DB
}
func (c Context) Error400(err error, message string, w http.ResponseWriter, path string, base string, data AnyMap) *Error {
c.SetReportCaller(true)
c.Logger.Error(message)
c.SetReportCaller(false)
c.SetReportCaller(true)
c.Logger.Error(message)
c.SetReportCaller(false)
if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", http.StatusBadRequest)
c.Logger.Error(err)
}
if c.Mode == JSON {
return &Error{http.StatusBadRequest, nil, c.AddMap(data)}
}
if c.Mode == JSON {
return &Error{http.StatusBadRequest, nil, c.AddMap(data)}
}
LoadDefineTemplate(w, path, base, c.AddMap(data))
return nil
LoadDefineTemplate(w, path, base, c.AddMap(data))
return nil
}
func (c Context) SetReportCaller(report bool) {
if (report) {
c.Logger.SetCallerOffset(2)
c.Logger.SetReportCaller(true)
} else {
c.Logger.SetCallerOffset(1)
c.Logger.SetReportCaller(false)
}
if report {
c.Logger.SetCallerOffset(2)
c.Logger.SetReportCaller(true)
} else {
c.Logger.SetCallerOffset(1)
c.Logger.SetReportCaller(false)
}
}
func (c Context) ErrorCode(err error, code int, data AnyMap) *Error {
if (code == 400) {
c.SetReportCaller(true)
c.Logger.Warn("When returning BadRequest(400) please use context.Error400\n")
c.SetReportCaller(false)
}
if code == 400 {
c.SetReportCaller(true)
c.Logger.Warn("When returning BadRequest(400) please use context.Error400\n")
c.SetReportCaller(false)
}
if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", code)
c.Logger.Error(err)
@@ -422,11 +422,11 @@ func (x Handle) createContext(handler *Handle, mode AnswerType, r *http.Request)
var token *string
logger := log.NewWithOptions(os.Stdout, log.Options{
ReportTimestamp: true,
TimeFormat: time.Kitchen,
Prefix: r.URL.Path,
})
logger := log.NewWithOptions(os.Stdout, log.Options{
ReportTimestamp: true,
TimeFormat: time.Kitchen,
Prefix: r.URL.Path,
})
for _, r := range r.Cookies() {
if r.Name == "auth" {
@@ -438,9 +438,9 @@ func (x Handle) createContext(handler *Handle, mode AnswerType, r *http.Request)
if token == nil {
return &Context{
Mode: mode,
Logger: logger,
Db: handler.Db,
Mode: mode,
Logger: logger,
Db: handler.Db,
}, nil
}
@@ -461,7 +461,7 @@ func Redirect(path string, mode AnswerType, w http.ResponseWriter, r *http.Reque
return
}
if mode&(HTMLFULL|HTML) != 0 {
w.Header().Add("HX-Redirect", path)
w.Header().Add("HX-Redirect", path)
w.WriteHeader(204)
} else {
w.WriteHeader(http.StatusSeeOther)
@@ -517,7 +517,7 @@ func (x Handle) StaticFiles(pathTest string, fileType string, contentType string
}
func ErrorCode(err error, code int, data AnyMap) *Error {
log.Warn("This function is deprecated please use the one provided by context")
log.Warn("This function is deprecated please use the one provided by context")
// TODO Improve Logging
if err != nil {
fmt.Printf("Something went wrong returning with: %d\n.Err:\n", code)
@@ -527,7 +527,7 @@ func ErrorCode(err error, code int, data AnyMap) *Error {
}
func Error500(err error) *Error {
log.Warn("This function is deprecated please use the one provided by context")
log.Warn("This function is deprecated please use the one provided by context")
return ErrorCode(err, http.StatusInternalServerError, nil)
}
@@ -556,6 +556,42 @@ func (x Handle) ReadFiles(pathTest string, baseFilePath string, fileType string,
})
}
func (x Handle) ReadTypesFiles(pathTest string, baseFilePath string, fileTypes []string, contentTypes []string) {
http.HandleFunc(pathTest, func(w http.ResponseWriter, r *http.Request) {
user_path := r.URL.Path[len(pathTest):]
// fmt.Printf("Requested path: %s\n", user_path)
found := false
index := -1;
for i, fileType := range fileTypes {
if strings.HasSuffix(user_path, fileType) {
found = true
index = i;
break
}
}
if !found {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("File not found"))
return
}
bytes, err := os.ReadFile(path.Join(baseFilePath, pathTest, user_path))
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to load file"))
return
}
w.Header().Set("Content-Type", contentTypes[index])
w.Write(bytes)
})
}
func NewHandler(db *sql.DB) *Handle {
var gets []HandleFunc