Format Go code with gofmt

Standardizes indentation from spaces to Go's canonical tab formatting.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Lucas 2025-06-14 02:31:17 +02:00
parent e95f47874a
commit 0f18a44eb8

340
main.go
View file

@ -1,74 +1,74 @@
package main package main
import ( import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
"strconv" "strconv"
"strings" "strings"
"time" "time"
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
) )
type Item struct { type Item struct {
ID int `json:"id"` ID int `json:"id"`
Name string `json:"name"` Name string `json:"name"`
} }
type UserInfo struct { type UserInfo struct {
Username string `json:"username"` Username string `json:"username"`
Name string `json:"name"` Name string `json:"name"`
Email string `json:"email"` Email string `json:"email"`
Groups string `json:"groups"` Groups string `json:"groups"`
Headers map[string]string `json:"headers"` Headers map[string]string `json:"headers"`
} }
var db *sql.DB var db *sql.DB
func initDB() { func initDB() {
var err error var err error
db, err = sql.Open("sqlite", "items.db") db, err = sql.Open("sqlite", "items.db")
if err != nil { if err != nil {
log.Fatal("Failed to open database:", err) log.Fatal("Failed to open database:", err)
} }
createTable := ` createTable := `
CREATE TABLE IF NOT EXISTS items ( CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL name TEXT NOT NULL
);` );`
_, err = db.Exec(createTable) _, err = db.Exec(createTable)
if err != nil { if err != nil {
log.Fatal("Failed to create table:", err) log.Fatal("Failed to create table:", err)
} }
} }
func main() { func main() {
if len(os.Args) > 1 && os.Args[1] == "--watch" { if len(os.Args) > 1 && os.Args[1] == "--watch" {
watchAndRestart() watchAndRestart()
return return
} }
// Initialize database // Initialize database
initDB() initDB()
defer db.Close() defer db.Close()
// Your actual API // Your actual API
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
http.HandleFunc("/randomnumber", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/randomnumber", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%d", rand.Intn(1000)) fmt.Fprintf(w, "%d", rand.Intn(1000))
}) })
http.HandleFunc("/slowtest", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/slowtest", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
fmt.Fprintf(w, "true") fmt.Fprintf(w, "true")
}) })
http.HandleFunc("/welcome", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/welcome", func(w http.ResponseWriter, r *http.Request) {
@ -93,172 +93,172 @@ func main() {
// Auth endpoints // Auth endpoints
http.HandleFunc("/auth/user", handleAuthUser) http.HandleFunc("/auth/user", handleAuthUser)
log.Println("API running on :3847") log.Println("API running on :3847")
http.ListenAndServe("127.0.0.1:3847", nil) http.ListenAndServe("127.0.0.1:3847", nil)
} }
func watchAndRestart() { func watchAndRestart() {
binaryPath, _ := os.Executable() binaryPath, _ := os.Executable()
var cmd *exec.Cmd var cmd *exec.Cmd
start := func() { start := func() {
if cmd != nil && cmd.Process != nil { if cmd != nil && cmd.Process != nil {
cmd.Process.Kill() cmd.Process.Kill()
} }
cmd = exec.Command(binaryPath) cmd = exec.Command(binaryPath)
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
cmd.Start() cmd.Start()
} }
start() // Initial start start() // Initial start
lastMod := getModTime(binaryPath) lastMod := getModTime(binaryPath)
for { for {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
if mod := getModTime(binaryPath); mod.After(lastMod) { if mod := getModTime(binaryPath); mod.After(lastMod) {
log.Println("Binary changed, restarting...") log.Println("Binary changed, restarting...")
lastMod = mod lastMod = mod
start() start()
} }
} }
} }
func getModTime(path string) time.Time { func getModTime(path string) time.Time {
info, _ := os.Stat(path) info, _ := os.Stat(path)
return info.ModTime() return info.ModTime()
} }
func handleItems(w http.ResponseWriter, r *http.Request) { func handleItems(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
switch r.Method { switch r.Method {
case "GET": case "GET":
getItems(w, r) getItems(w, r)
case "POST": case "POST":
createItem(w, r) createItem(w, r)
default: default:
w.WriteHeader(http.StatusMethodNotAllowed) w.WriteHeader(http.StatusMethodNotAllowed)
json.NewEncoder(w).Encode(map[string]string{"error": "Method not allowed"}) json.NewEncoder(w).Encode(map[string]string{"error": "Method not allowed"})
} }
} }
func getItems(w http.ResponseWriter, r *http.Request) { func getItems(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query("SELECT id, name FROM items ORDER BY id") rows, err := db.Query("SELECT id, name FROM items ORDER BY id")
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to fetch items"}) json.NewEncoder(w).Encode(map[string]string{"error": "Failed to fetch items"})
return return
} }
defer rows.Close() defer rows.Close()
var items []Item var items []Item
for rows.Next() { for rows.Next() {
var item Item var item Item
err := rows.Scan(&item.ID, &item.Name) err := rows.Scan(&item.ID, &item.Name)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to scan items"}) json.NewEncoder(w).Encode(map[string]string{"error": "Failed to scan items"})
return return
} }
items = append(items, item) items = append(items, item)
} }
// Ensure we always return an array, even if empty // Ensure we always return an array, even if empty
if items == nil { if items == nil {
items = []Item{} items = []Item{}
} }
json.NewEncoder(w).Encode(items) json.NewEncoder(w).Encode(items)
} }
func createItem(w http.ResponseWriter, r *http.Request) { func createItem(w http.ResponseWriter, r *http.Request) {
var item Item var item Item
err := json.NewDecoder(r.Body).Decode(&item) err := json.NewDecoder(r.Body).Decode(&item)
if err != nil { if err != nil {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid JSON"}) json.NewEncoder(w).Encode(map[string]string{"error": "Invalid JSON"})
return return
} }
if item.Name == "" { if item.Name == "" {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Name is required"}) json.NewEncoder(w).Encode(map[string]string{"error": "Name is required"})
return return
} }
result, err := db.Exec("INSERT INTO items (name) VALUES (?)", item.Name) result, err := db.Exec("INSERT INTO items (name) VALUES (?)", item.Name)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to create item"}) json.NewEncoder(w).Encode(map[string]string{"error": "Failed to create item"})
return return
} }
id, _ := result.LastInsertId() id, _ := result.LastInsertId()
item.ID = int(id) item.ID = int(id)
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(item) json.NewEncoder(w).Encode(item)
} }
func handleItemDelete(w http.ResponseWriter, r *http.Request) { func handleItemDelete(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
if r.Method != "DELETE" { if r.Method != "DELETE" {
w.WriteHeader(http.StatusMethodNotAllowed) w.WriteHeader(http.StatusMethodNotAllowed)
json.NewEncoder(w).Encode(map[string]string{"error": "Method not allowed"}) json.NewEncoder(w).Encode(map[string]string{"error": "Method not allowed"})
return return
} }
// Extract ID from URL path /items/{id} // Extract ID from URL path /items/{id}
path := strings.TrimPrefix(r.URL.Path, "/items/") path := strings.TrimPrefix(r.URL.Path, "/items/")
id, err := strconv.Atoi(path) id, err := strconv.Atoi(path)
if err != nil { if err != nil {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid item ID"}) json.NewEncoder(w).Encode(map[string]string{"error": "Invalid item ID"})
return return
} }
result, err := db.Exec("DELETE FROM items WHERE id = ?", id) result, err := db.Exec("DELETE FROM items WHERE id = ?", id)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to delete item"}) json.NewEncoder(w).Encode(map[string]string{"error": "Failed to delete item"})
return return
} }
rowsAffected, _ := result.RowsAffected() rowsAffected, _ := result.RowsAffected()
if rowsAffected == 0 { if rowsAffected == 0 {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{"error": "Item not found"}) json.NewEncoder(w).Encode(map[string]string{"error": "Item not found"})
return return
} }
json.NewEncoder(w).Encode(map[string]string{"message": "Item deleted successfully"}) json.NewEncoder(w).Encode(map[string]string{"message": "Item deleted successfully"})
} }
func handleAuthUser(w http.ResponseWriter, r *http.Request) { func handleAuthUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
if r.Method != "GET" { if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed) w.WriteHeader(http.StatusMethodNotAllowed)
json.NewEncoder(w).Encode(map[string]string{"error": "Method not allowed"}) json.NewEncoder(w).Encode(map[string]string{"error": "Method not allowed"})
return return
} }
// Collect all headers for debugging // Collect all headers for debugging
headers := make(map[string]string) headers := make(map[string]string)
for name, values := range r.Header { for name, values := range r.Header {
headers[name] = strings.Join(values, ", ") headers[name] = strings.Join(values, ", ")
} }
// Extract common Authelia headers // Extract common Authelia headers
userInfo := UserInfo{ userInfo := UserInfo{
Username: r.Header.Get("Remote-User"), Username: r.Header.Get("Remote-User"),
Name: r.Header.Get("Remote-Name"), Name: r.Header.Get("Remote-Name"),
Email: r.Header.Get("Remote-Email"), Email: r.Header.Get("Remote-Email"),
Groups: r.Header.Get("Remote-Groups"), Groups: r.Header.Get("Remote-Groups"),
Headers: headers, Headers: headers,
} }
json.NewEncoder(w).Encode(userInfo) json.NewEncoder(w).Encode(userInfo)
} }