errorhandling und logging eingebunden, code überarbeitet

This commit is contained in:
xoy 2023-01-28 21:43:07 +01:00
parent 0c8813addf
commit 0a1846adb8
6 changed files with 84 additions and 63 deletions

1
config/http.yml Normal file
View File

@ -0,0 +1 @@
address: :80

View File

@ -8,10 +8,7 @@ import (
func dbConnect(username string, password string, address string, port string, database string) *sql.DB { func dbConnect(username string, password string, address string, port string, database string) *sql.DB {
db, err := sql.Open("mysql", username+":"+password+"@tcp("+address+":"+port+")/"+database) db, err := sql.Open("mysql", username+":"+password+"@tcp("+address+":"+port+")/"+database)
errorPanic(err)
if err != nil {
panic(err.Error())
}
return db return db
} }
@ -22,9 +19,7 @@ func dbClose(database *sql.DB) {
func dbQuerry(database *sql.DB, sqlCode string) *sql.Rows { func dbQuerry(database *sql.DB, sqlCode string) *sql.Rows {
results, err := database.Query(sqlCode) results, err := database.Query(sqlCode)
if err != nil { errorPanic(err)
panic(err.Error())
}
return results return results
} }

14
file.go
View File

@ -2,15 +2,21 @@ package main
import ( import (
"io/ioutil" "io/ioutil"
"log" "os"
) )
func fileRead(src string) string { func fileRead(src string) string {
content, err := ioutil.ReadFile(src) content, err := ioutil.ReadFile(src)
if err != nil { errorPanic(err)
log.Fatal(err.Error())
}
return string(content) return string(content)
} }
func fileAddLine(input string, filepath string) {
file, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
errorPanic(err)
_, err = file.WriteString(input + "\n")
errorPanic(err)
}

100
func.go
View File

@ -2,35 +2,44 @@ package main
import ( import (
"io" "io"
"math/rand"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"time" "time"
) )
func logger(input string) {
println(input)
fileAddLine(input, "./log/"+time.Now().Format("2006-02-01")+".log")
}
func handler() { func handler() {
//Pages logger("Pages:")
//pages
httpHandleFunc("", "./web/pages/home.html", "text/html") httpHandleFunc("", "./web/pages/home.html", "text/html")
httpHandleFunc("home", "./web/pages/home.html", "text/html") httpHandleFunc("home", "./web/pages/home.html", "text/html")
httpHandleFunc("treff", "./web/pages/treff.html", "text/html") httpHandleFunc("treff", "./web/pages/treff.html", "text/html")
httpHandleFunc("events", "./web/pages/events.html", "text/html") httpHandleFunc("events", "./web/pages/events.html", "text/html")
httpHandleFunc("about", "./web/pages/about.html", "text/html") httpHandleFunc("about", "./web/pages/about.html", "text/html")
//contact pages
httpHandleFunc("kontakt", "./web/pages/kontakt.html", "text/html") httpHandleFunc("kontakt", "./web/pages/kontakt.html", "text/html")
httpHandleFunc("kontakt/adresse", "./web/pages/kontakt/adresse.html", "text/html") httpHandleFunc("kontakt/adresse", "./web/pages/kontakt/adresse.html", "text/html")
httpHandleFunc("kontakt/irc", "./web/pages/kontakt/irc.html", "text/html") httpHandleFunc("kontakt/irc", "./web/pages/kontakt/irc.html", "text/html")
httpHandleFunc("kontakt/mail", "./web/pages/kontakt/mail.html", "text/html") httpHandleFunc("kontakt/mail", "./web/pages/kontakt/mail.html", "text/html")
httpHandleFunc("kontakt/tel", "./web/pages/kontakt/tel.html", "text/html") httpHandleFunc("kontakt/tel", "./web/pages/kontakt/tel.html", "text/html")
//pages
httpHandleFunc("verein", "./web/pages/verein.html", "text/html") httpHandleFunc("verein", "./web/pages/verein.html", "text/html")
httpHandleFunc("support", "./web/pages/support.html", "text/html") httpHandleFunc("support", "./web/pages/support.html", "text/html")
httpHandleFunc("impressum", "./web/pages/impressum.html", "text/html") httpHandleFunc("impressum", "./web/pages/impressum.html", "text/html")
httpHandleFunc("datenschutz", "./web/pages/datenschutz.html", "text/html") httpHandleFunc("datenschutz", "./web/pages/datenschutz.html", "text/html")
//admin pages
keys := getAdminKeys() keys := getAdminKeys()
//this check is necessary!
if keys != nil { if keys != nil {
for _, key := range keys { for _, key := range keys {
httpHandleFunc("admin/"+key, "./web/pages/admin/dashboard.html", "text/html") httpHandleFunc("admin/"+key, "./web/pages/admin/dashboard.html", "text/html")
@ -38,13 +47,13 @@ func handler() {
} }
} }
//Styles //styles
httpHandleFunc("style/main.css", "./web/styles/main.css", "text/css") httpHandleFunc("style/main.css", "./web/styles/main.css", "text/css")
httpHandleFunc("style/kontakt.css", "./web/styles/kontakt.css", "text/css") httpHandleFunc("style/kontakt.css", "./web/styles/kontakt.css", "text/css")
httpHandleFunc("style/home.css", "./web/styles/home.css", "text/css") httpHandleFunc("style/home.css", "./web/styles/home.css", "text/css")
httpHandleFunc("style/events.css", "./web/styles/events.css", "text/css") httpHandleFunc("style/events.css", "./web/styles/events.css", "text/css")
//Images //images
httpHandleFunc("image/logo_ctdo.svg", "./web/images/logo_ctdo.svg", "image/svg+xml") httpHandleFunc("image/logo_ctdo.svg", "./web/images/logo_ctdo.svg", "image/svg+xml")
httpHandleFunc("image/header.jpg", "./web/images/header.jpg", "image/jpeg") httpHandleFunc("image/header.jpg", "./web/images/header.jpg", "image/jpeg")
httpHandleFunc("image/adresse_knopf.webp", "./web/images/adresse_knopf.webp", "image/webp") httpHandleFunc("image/adresse_knopf.webp", "./web/images/adresse_knopf.webp", "image/webp")
@ -84,10 +93,9 @@ func getRoomState() status {
} }
defer r.Body.Close() defer r.Body.Close()
body, _err := io.ReadAll(r.Body) var body []byte
if _err != nil { body, err = io.ReadAll(r.Body)
panic(_err.Error()) errorPanic(err)
}
bodyString := string(body) bodyString := string(body)
@ -96,21 +104,18 @@ func getRoomState() status {
bodyString = strings.ReplaceAll(bodyString, "{", "") bodyString = strings.ReplaceAll(bodyString, "{", "")
bodyString = strings.ReplaceAll(bodyString, "}", "") bodyString = strings.ReplaceAll(bodyString, "}", "")
_temp := strings.Split(bodyString, ",") Temp := strings.Split(bodyString, ",")
for _, element := range _temp { for _, element := range Temp {
__temp := strings.Split(element, ":") TEmp := strings.Split(element, ":")
temp = append(temp, __temp[1]) temp = append(temp, TEmp[1])
} }
roomState := new(status) roomState := new(status)
roomState.state = temp[0] == "true" roomState.state = temp[0] == "true"
var __err error roomState.power, err = strconv.ParseInt(temp[2], 0, 64)
roomState.power, __err = strconv.ParseInt(temp[2], 0, 64) errorPanic(err)
if __err != nil {
panic(__err.Error())
}
return *roomState return *roomState
} }
@ -211,14 +216,10 @@ func getNextTopic() topic {
if newDate[0] == "Thu" || newDate[0] == "Tue" { if newDate[0] == "Thu" || newDate[0] == "Tue" {
dayA, errA := strconv.Atoi(newDate[2]) dayA, errA := strconv.Atoi(newDate[2])
if errA != nil { errorPanic(errA)
panic(errA.Error())
}
dayB, errB := strconv.Atoi(newDate[2]) dayB, errB := strconv.Atoi(newDate[2])
if errB != nil { errorPanic(errB)
panic(errB.Error())
}
if ifFloatRange(float64(dayA)/7, 0, 1, false, true) || (ifFloatRange(float64(dayB)/7, 2, 3, false, true) && newDate[0] == "Tue") { if ifFloatRange(float64(dayA)/7, 0, 1, false, true) || (ifFloatRange(float64(dayB)/7, 2, 3, false, true) && newDate[0] == "Tue") {
output.date = date.AddDate(0, 0, 1*i).Format("02.01.2006") output.date = date.AddDate(0, 0, 1*i).Format("02.01.2006")
@ -246,34 +247,61 @@ func readDatabaseYML() database {
switch i { switch i {
case 0: case 0:
output.username = row[1] output.username = row[1]
break
case 1: case 1:
output.password = row[1] output.password = row[1]
break
case 2: case 2:
output.address = row[1] output.address = row[1]
break
case 3: case 3:
output.port = row[1] output.port = row[1]
break
case 4: case 4:
output.database = row[1] output.database = row[1]
break default:
logger("func.go:259 -> switch-case is out of range")
} }
} }
return *output return *output
} }
func generateRandomString(length int) string { func readHttpYML() string {
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZ" file := fileRead("./config/http.yml")
chars += strings.ToLower(chars)
output := "" rows := [][]string{}
for i := 0; i < length; i++ { for _, row := range strings.Split(file, "\n") {
output += string(chars[rand.Intn(len(chars)-1)]) rows = append(rows, strings.Split(row, ": "))
} }
return output for i, row := range rows {
switch i {
case 0:
return row[1]
default:
logger("func.go:280 -> switch-case is out of range")
}
}
return ""
}
/*
func generateRandomString(length int) string {
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars += strings.ToLower(chars)
output := ""
for i := 0; i < length; i++ {
output += string(chars[rand.Intn(len(chars)-1)])
}
return output
}
*/
func errorPanic(err error) {
if err != nil {
logger(err.Error())
panic("----------------ERROR----------------")
}
} }

View File

@ -6,8 +6,7 @@ import (
) )
func httpHandleFunc(urlPath string, filepath string, contentType string) { func httpHandleFunc(urlPath string, filepath string, contentType string) {
s := new(submit) logger("-->" + urlPath + " " + filepath + " " + contentType)
s.data = "null"
http.HandleFunc("/"+urlPath, func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/"+urlPath, func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", contentType) w.Header().Add("Content-Type", contentType)
@ -20,9 +19,8 @@ func httpHandleFuncWithPOST(urlPath string, filepath string, contentType string)
s.data = "null" s.data = "null"
http.HandleFunc("/"+urlPath, func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/"+urlPath, func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" { if r.Method == "POST" {
if err := r.ParseForm(); err != nil { err := r.ParseForm()
panic(err.Error()) errorPanic(err)
}
} }
w.Header().Add("Content-Type", contentType) w.Header().Add("Content-Type", contentType)

15
main.go
View File

@ -1,23 +1,16 @@
package main package main
import ( import (
"errors"
"fmt"
"net/http" "net/http"
"os"
) )
func main() { func main() {
addr := ":80" addr := readHttpYML()
logger("Connection open with address " + addr)
handler() handler()
err := http.ListenAndServe(addr, nil) err := http.ListenAndServe(addr, nil)
errorPanic(err)
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
} else if err != nil {
fmt.Printf("error starting server: %s\n", err)
os.Exit(1)
}
} }