86 lines
2.1 KiB
Go
86 lines
2.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
|
||
|
"github.com/gorilla/mux"
|
||
|
)
|
||
|
|
||
|
// GetUsersHandler handles GET requests to /admin/user
|
||
|
func GetUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
var users []User
|
||
|
db.Find(&users)
|
||
|
json.NewEncoder(w).Encode(users)
|
||
|
}
|
||
|
|
||
|
// CreateUserHandler handles POST requests to /admin/user
|
||
|
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
var user User
|
||
|
err := json.NewDecoder(r.Body).Decode(&user)
|
||
|
if err != nil {
|
||
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
db.Create(&user)
|
||
|
json.NewEncoder(w).Encode(user)
|
||
|
}
|
||
|
|
||
|
// GetUserHandler handles GET requests to /admin/user/{id}
|
||
|
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
vars := mux.Vars(r)
|
||
|
id := vars["id"]
|
||
|
var user User
|
||
|
db.First(&user, id)
|
||
|
if user.ID == 0 {
|
||
|
http.Error(w, "User not found", http.StatusNotFound)
|
||
|
return
|
||
|
}
|
||
|
json.NewEncoder(w).Encode(user)
|
||
|
}
|
||
|
|
||
|
// DeleteUserHandler handles DELETE requests to /admin/user/{id}
|
||
|
func DeleteUserHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
vars := mux.Vars(r)
|
||
|
id := vars["id"]
|
||
|
var user User
|
||
|
db.First(&user, id)
|
||
|
if user.ID == 0 {
|
||
|
http.Error(w, "User not found", http.StatusNotFound)
|
||
|
return
|
||
|
}
|
||
|
db.Delete(&user)
|
||
|
w.WriteHeader(http.StatusNoContent)
|
||
|
}
|
||
|
|
||
|
// BackupDatabaseHandler handles GET requests to /admin/db
|
||
|
func BackupDatabaseHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
// ...
|
||
|
fmt.Println("BackupDatabaseHandler called")
|
||
|
// Open the database file using the path from the config
|
||
|
file, err := os.Open(config.DatabasePath)
|
||
|
if err != nil {
|
||
|
http.Error(w, "Failed to open database file", http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
defer file.Close()
|
||
|
|
||
|
// Copy the file to the response writer
|
||
|
_, err = io.Copy(w, file)
|
||
|
if err != nil {
|
||
|
http.Error(w, "Failed to send database file", http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// RestoreDatabaseHandler handles POST requests to /admin/db
|
||
|
func RestoreDatabaseHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
// implement database restore logic here
|
||
|
fmt.Println("Restoring database...")
|
||
|
// ...
|
||
|
w.WriteHeader(http.StatusOK)
|
||
|
}
|