Merge is necessary due to poor repository hygiene.

Merge branch 'api' of gitea.r8z.us:stwhite/boxes-api into api
This commit is contained in:
Steve White 2024-10-23 17:03:06 -05:00
commit 44c615a120
5 changed files with 70 additions and 3 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
data/*
images/*
.DS_Store
build/*

View File

@ -16,6 +16,8 @@ type Config struct {
ImageStorageDir string `yaml:"image_storage_dir"`
ListeningPort int `yaml:"listening_port"`
LogFile string `yaml:"log_file"`
StaticFilesDir string `yaml:"static_files_dir"`
AllowedOrigins string `yaml:"allowed_origins"`
}
func LoadConfig(configPath string) (*Config, error) {
@ -37,5 +39,13 @@ func LoadConfig(configPath string) (*Config, error) {
config.DatabasePath = dbPath
}
if config.StaticFilesDir == "" {
config.StaticFilesDir = "build"
}
if config.AllowedOrigins == "" {
config.AllowedOrigins = "http://localhost:3000"
}
return &config, nil
}

View File

@ -4,3 +4,5 @@ jwt_secret: "super_secret_key"
image_storage_dir: "images"
listening_port: 8080
log_file: "boxes.log"
static_files_dir: "/app/build/"
allowed_origins: "*"

22
docker-compose.yml Normal file
View File

@ -0,0 +1,22 @@
version: '3.3' # Specify the Docker Compose file version
services:
boxes-api:
image: boxes-api:latest # Use the existing boxes-api image
container_name: boxes-api # Name the container
ports:
- "8080:8080" # Map host port 8080 to container port 8080
environment:
BOXES_API_CONFIG: "/app/config/config.yaml" # Set the CONFIG environment variable
volumes:
- /home/stwhite/dockerboxes/boxes-api/data:/app/data # Mount host data directory
- /home/stwhite/dockerboxes/boxes-api/images:/app/images # Mount host images directory
- /home/stwhite/dockerboxes/boxes-api/config:/app/config # Mount host config directory
- /home/stwhite/dockerboxes/boxes-api/build:/app/build
networks:
- app-network
networks:
app-network:
driver: bridge

36
main.go
View File

@ -6,6 +6,7 @@ import (
"net/http"
"os"
"strings"
"path/filepath"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
@ -23,9 +24,18 @@ func main() {
var err error
config, err = LoadConfig(configFile)
// get the static files directory
staticPath := config.StaticFilesDir
// Add this before setting up the handler
if _, err := os.Stat(staticPath); os.IsNotExist(err) {
log.Fatalf("Static directory does not exist: %s", staticPath)
}
// Get the allowed origins from the ALLOWED_ORIGINS environment variable
// If empty, defaults to http://localhost:3000
allowedOrigins := os.Getenv("BOXES_API_ALLOWED_ORIGINS")
allowedOrigins := config.AllowedOrigins
fmt.Println("Allowed origins: ", allowedOrigins)
origins := []string{"http://localhost:3000"} // Default value
if allowedOrigins != "" {
@ -52,12 +62,25 @@ func main() {
}
defer db.Close()
// Modify your custom handler to include more detailed logging
customHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Attempting to serve: %s from directory: %s", r.URL.Path, staticPath)
fullPath := filepath.Join(staticPath, r.URL.Path)
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
log.Printf("File not found: %s", fullPath)
http.NotFound(w, r)
return
}
http.FileServer(http.Dir(staticPath)).ServeHTTP(w, r)
})
fmt.Println("Default user 'boxuser' created successfully!")
// Create the router
baseRouter := mux.NewRouter()
router := baseRouter.PathPrefix("/api/v1").Subrouter()
staticRouter := baseRouter.PathPrefix("/").Subrouter()
// Define your routes
router.Handle("/login", http.HandlerFunc(LoginHandler)).Methods("POST", "OPTIONS")
@ -90,6 +113,15 @@ func main() {
managementRouter.Handle("/db", http.HandlerFunc(RestoreDatabaseHandler)).Methods("POST", "OPTIONS")
managementRouter.Handle("/imagearchive", http.HandlerFunc(GetImageArchiveHandler)).Methods("GET", "OPTIONS")
// Define a route for serving static files
fmt.Println("Serving static files from:", staticPath)
//staticHandler := http.FileServer(http.Dir(staticPath))
fmt.Println("Registering route for serving static files, no StripPrefix")
//staticRouter.HandleFunc("/", customHandler).Methods("GET", "OPTIONS")
// perplexity recommends:
staticRouter.PathPrefix("/").Handler(http.StripPrefix("/", customHandler))
// Apply CORS middleware
c := cors.New(cors.Options{
AllowedOrigins: origins,
@ -101,5 +133,5 @@ func main() {
// Start the server with CORS middleware
fmt.Printf("Server listening on port %d\n", config.ListeningPort)
http.ListenAndServe(fmt.Sprintf(":%d", config.ListeningPort), c.Handler(router))
http.ListenAndServe(fmt.Sprintf(":%d", config.ListeningPort), c.Handler(baseRouter))
}