working on templating

This commit is contained in:
mykola2312 2024-11-23 06:50:15 +02:00
parent 024575c753
commit 30c71fdc19
5 changed files with 84 additions and 5 deletions

60
main.go
View file

@ -1,11 +1,58 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"text/template"
"wargh/db"
)
var templates *template.Template
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
//templates.Lookup("index.html").Execute(w, nil)
redirectError(w, r, ERROR_TEST)
}
}
const (
ERROR_UNKNOWN = 0
ERROR_TEST = 1
)
var ERROR_TEXT = []string{
"Unknown error",
"Test error",
}
func errorHandler(w http.ResponseWriter, r *http.Request) {
errorParam := r.URL.Query().Get("error")
var errorCode int
if errorParam != "" {
var err error
errorCode, err = strconv.Atoi(errorParam)
if err != nil {
errorCode = 0
}
} else {
errorCode = 0
}
if errorCode < 0 || errorCode >= len(ERROR_TEXT) {
errorCode = 0
}
templates.Lookup("error.html").Execute(w, ERROR_TEXT[errorCode])
}
func redirectError(w http.ResponseWriter, r *http.Request, errorCode int) {
http.Redirect(w, r, fmt.Sprintf("/error?error=%d", errorCode), http.StatusSeeOther)
}
func main() {
db.Init(&db.DBConfig{
DBPath: "wargh.db",
@ -18,4 +65,17 @@ func main() {
os.Exit(1)
}
defer DB.Close()
templates, err = template.New("templates").ParseFiles(
"templates/index.html",
"templates/error.html",
)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", indexHandler)
http.HandleFunc("/error", errorHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

View file

@ -1,4 +1,5 @@
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
test TEXT NOT NULL UNIQUE
);
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
login TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
);

View file

@ -11,7 +11,7 @@ The 'index' page should display list of archives: name and follow link.
The follow link must redirect to storage archive/, which by itself
should be served by NGINX
'login' is for admin authorization, which should create session cookie.
'login' is for admin authorization, which should create session cookie. when no admin user exists, creates new.
'add-existing' - form to add archive with name and already existing directory
'wget' - creates recursive wget job
'job' - monitor of job stdout

9
templates/error.html Normal file
View file

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<title>wargh - error</title>
</head>
<bodY>
<h1>{{.}}</h1>
</bodY>
</html>

9
templates/index.html Normal file
View file

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<title>wargh - index</title>
</head>
<bodY>
<h1>Index</h1>
</bodY>
</html>