Skip to content

Commit

Permalink
closer still
Browse files Browse the repository at this point in the history
  • Loading branch information
Dokotela committed Nov 20, 2024
1 parent f86bd15 commit d1c9ce5
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 85 deletions.
6 changes: 3 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import "github.com/fhir-fli/pocketfhir/pocketfhir"
func main() {
// Use the string wrapper for local development
dataDir := "./assets"
hostname := "127.0.0.1"
ipAddress := "127.0.0.1"
port := "8080" // Changed from 443 to 8080 to avoid permission issues
getApiLogs := false
enableApiLogs := false

pocketfhir.RunServer(dataDir, hostname, port, getApiLogs)
pocketfhir.RunServer(dataDir, ipAddress, port, enableApiLogs)
}
157 changes: 86 additions & 71 deletions pocketfhir/caddy.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,79 +11,89 @@ import (
)

// CreateConfig generates a basic Caddy configuration to run a reverse proxy with HTTPS.
func CreateConfig(port, upstreamURL, storagePath, certFile, keyFile string) *caddy.Config {
func CreateConfig(pbPort, httpPort, httpsPort, pbUrl, storagePath string) *caddy.Config {
// Use storagePath for the log file paths
caddyDebugLogPath := fmt.Sprintf("%s/caddy_debug.log", storagePath)
accessLogPath := fmt.Sprintf("%s/access_log.log", storagePath)
// Define where certificates should be stored
certificateStoragePath := fmt.Sprintf("%s/caddy_certs", storagePath)

// JSON Configuration with dynamically inserted paths and certificates
// JSON Configuration with dynamically inserted paths
jsonConfig := fmt.Sprintf(`{
"logging": {
"logs": {
"default": {
"level": "DEBUG",
"writer": {
"output": "file",
"filename": "%s"
}
},
"http.access": {
"level": "DEBUG",
"writer": {
"output": "file",
"filename": "%s"
},
"encoder": {
"format": "json"
}
}
}
},
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":%s"
],
"routes": [
{
"handle": [
{
"handler": "request_body",
"max_size": 10000000
},
{
"handler": "reverse_proxy",
"transport": {
"protocol": "http",
"read_timeout": 360000000000
},
"upstreams": [
{
"dial": "127.0.0.1:8090"
}
]
}
]
}
]
}
}
}
},
"tls": {
"certificates": {
"automate": ["*"],
"load_files": [
{
"certificate": "%s",
"key": "%s"
}
]
}
}
}`, caddyDebugLogPath, accessLogPath, port, certFile, keyFile)
"logging": {
"logs": {
"default": {
"level": "DEBUG",
"writer": {
"output": "file",
"filename": "%s"
}
},
"http.access": {
"level": "DEBUG",
"writer": {
"output": "file",
"filename": "%s"
},
"encoder": {
"format": "json"
}
}
}
},
"storage": {
"module": "file_system",
"root": "%s"
},
"apps": {
"http": {
"http_port": %s,
"https_port": %s,
"servers": {
"srv0": {
"listen": [
":%s"
],
"routes": [
{
"handle": [
{
"handler": "request_body",
"max_size": 10000000
},
{
"handler": "reverse_proxy",
"transport": {
"protocol": "http",
"read_timeout": 360000000000
},
"upstreams": [
{
"dial": "%s:%s"
}
]
}
]
}
]
}
}
},
"tls": {
"automation": {
"policies": [
{
"issuers": [
{
"module": "internal"
}
]
}
]
}
}
}
}`, caddyDebugLogPath, accessLogPath, certificateStoragePath, httpPort, httpsPort, httpsPort, pbUrl, pbPort)

// Parse the JSON into a caddy.Config struct
var caddyConfig caddy.Config
Expand All @@ -98,17 +108,22 @@ func CreateConfig(port, upstreamURL, storagePath, certFile, keyFile string) *cad
}

// StartCaddy starts the Caddy server with the provided configuration.
func StartCaddy(port, upstreamURL, storagePath, certFile, keyFile string) {
func StartCaddy(pbPort, httpPort, httpsPort, pbUrl, storagePath string) {
// Change working directory
if err := os.Chdir(storagePath); err != nil {
log.Fatalf("Failed to change working directory to %s: %v", storagePath, err)
}

// Log configuration for transparency
log.Printf("Starting Caddy with configuration:\nPort: %s\nUpstreamURL: %s\nStoragePath: %s\nCertFile: %s\nKeyFile: %s\n", port, upstreamURL, storagePath, certFile, keyFile)
log.Printf("Starting Caddy server with the following configuration:")
log.Printf("PocketBase Port: %s", pbPort)
log.Printf("HTTP Port: %s", httpPort)
log.Printf("HTTPS Port: %s", httpsPort)
log.Printf("Upstream URL: %s", pbUrl)
log.Printf("Storage Path: %s", storagePath)

// Generate Caddy config
cfg := CreateConfig(port, upstreamURL, storagePath, certFile, keyFile)
cfg := CreateConfig(pbPort, httpPort, httpsPort, pbUrl, storagePath)

// Serialize for debugging
configJSON, err := json.MarshalIndent(cfg, "", " ")
Expand Down
14 changes: 7 additions & 7 deletions pocketfhir/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ func RegisterNativeBridgeCallback(c NativeBridge) {
}

// RunServer starts the PocketFHIR server
func RunServer(dataDir string, hostname string, port string, getApiLogs bool) {
func RunServer(dataDir string, ipAddress string, pbPort string, enableApiLogs bool) {
// Set CLI-like arguments for PocketBase to specify server address and port
log.Printf("[DEBUG] Setting CLI arguments for server address and port: %s:%s\n", hostname, port)
os.Args = append(os.Args[:1], "serve", "--http", fmt.Sprintf("%s:%s", hostname, port))
log.Printf("[DEBUG] Setting CLI arguments for server address and port: %s:%s\n", ipAddress, pbPort)
os.Args = append(os.Args[:1], "serve", "--http", fmt.Sprintf("%s:%s", ipAddress, pbPort))

// Create a configuration object with custom settings
log.Println("[DEBUG] Creating PocketBase configuration object...")
config := pocketbase.Config{
DefaultDataDir: dataDir,
DefaultDev: getApiLogs, // Enabling dev mode for detailed logging
DefaultDev: enableApiLogs, // Enabling dev mode for detailed logging
HideStartBanner: false,
}

Expand Down Expand Up @@ -62,7 +62,7 @@ func RunServer(dataDir string, hostname string, port string, getApiLogs bool) {

// Setup additional native callbacks and routes
log.Println("[DEBUG] Setting up PocketBase callbacks and routes...")
setupPocketbaseCallbacks(app, getApiLogs)
setupPocketbaseCallbacks(app, enableApiLogs)
log.Println("[DEBUG] PocketBase callbacks and routes set up.")

// Initialize collections if necessary
Expand Down Expand Up @@ -107,13 +107,13 @@ func sendCommand(command string, data string) string {
}

// setupPocketbaseCallbacks sets up additional callbacks and native routes for PocketBase
func setupPocketbaseCallbacks(app *pocketbase.PocketBase, getApiLogs bool) {
func setupPocketbaseCallbacks(app *pocketbase.PocketBase, enableApiLogs bool) {
// Setup callbacks
log.Println("[DEBUG] Setting up OnBeforeServe callback...")
app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
log.Println("[DEBUG] OnBeforeServe triggered.")
sendCommand("OnBeforeServe", "")
if getApiLogs {
if enableApiLogs {
log.Println("[DEBUG] Adding API logs middleware...")
e.Router.Use(ApiLogsMiddleWare(app))
}
Expand Down
8 changes: 4 additions & 4 deletions pocketfhir/start.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package pocketfhir

import (
"fmt"
"log"
"os"
"os/signal"
Expand All @@ -10,7 +9,8 @@ import (
_ "github.com/caddyserver/caddy/v2/modules/standard"
)

func StartPocketFHIR(dataDir string, hostname string, port string, getApiLogs bool, caddyPort string, caddyStoragePath string, certFile string, keyFile string) {
func StartPocketFHIR(
pbPort string, httpPort string, httpsPort string, pbUrl string, ipAddress string, dataDir string, enableApiLogs bool, storagePath string) {
// Set environment variables for PocketBase configuration
log.Println("[DEBUG] Setting environment variables...")
if err := os.Setenv("POCKETBASE_DATA_DIR", dataDir); err != nil {
Expand All @@ -25,13 +25,13 @@ func StartPocketFHIR(dataDir string, hostname string, port string, getApiLogs bo
// Start the PocketFHIR server in a separate goroutine
go func() {
log.Println("[DEBUG] Starting PocketFHIR server...")
RunServer(dataDir, hostname, port, getApiLogs)
RunServer(dataDir, pbUrl, pbPort, enableApiLogs)
}()

// Start the Caddy server in a separate goroutine
go func() {
log.Println("[DEBUG] Starting Caddy server with HTTPS...")
StartCaddy(caddyPort, fmt.Sprintf("http://%s:%s", hostname, port), caddyStoragePath, certFile, keyFile)
StartCaddy(pbPort, httpPort, httpsPort, pbUrl, storagePath)
}()

// Wait for interrupt signal to gracefully shut down the server
Expand Down

0 comments on commit d1c9ce5

Please sign in to comment.