init commit

This commit is contained in:
2024-09-05 16:09:33 +02:00
commit d8cf7a2c69
9 changed files with 334 additions and 0 deletions

90
Backend/main.go Normal file
View File

@@ -0,0 +1,90 @@
package main
import (
"Backend/models"
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
_ "github.com/lib/pq"
)
var DB *sql.DB
func main() {
var err error
dbConnStr := getDBConn()
DB, err = sql.Open("postgres", dbConnStr)
if err!= nil {
log.Fatal(err)
}
defer DB.Close()
http.HandleFunc("/time", timeHandler)
fmt.Println("Server is running at http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func timeHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "PUT":
createBooking(w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func createBooking(w http.ResponseWriter, r *http.Request) {
booking := getBooking(r.URL.Query())
if models.VerifyBooking(booking) {
err := models.InsertBooking(booking, DB)
if err == fmt.Errorf("the same booking already exists") {
http.Error(w, "Booking already exists", http.StatusConflict)
return
}
if err != nil {
log.Println("Error inserting booking: ", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(booking)
}
w.WriteHeader(http.StatusBadRequest)
}
func getBooking(query_params url.Values) models.Booking {
bookingType, err := strconv.Atoi(query_params.Get("bookingType"))
if err!= nil {
log.Println("Error parsing bookingType: ", err)
return models.Booking{}
}
return models.Booking{
CradID: query_params.Get("cardID"),
ReaderID: query_params.Get("readerID"),
BookingType: bookingType,
}
}
func getDBConn() string {
dbHost := getEnv("POSTGRES_HOST", "localhost")
dbName := getEnv("POSTGRES_DB", "arbeitszeitmessung")
dbUser := getEnv("POSTGRES_USER", "arbeit_zeit")
dbPassword := getEnv("POSTGRES_PASS", "password")
return fmt.Sprintf("postgres://%s:%s@%s:5432/%s?sslmode=disable", dbUser, dbPassword, dbHost, dbName)
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}