Added API Endpoint and Admin Dashboard Endpoint
This commit is contained in:
parent
48f62500d5
commit
8ec5472355
23
cmd/serve.go
23
cmd/serve.go
@ -1,14 +1,31 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"printer.backend/internal/server"
|
||||
)
|
||||
|
||||
var serveCmd = &cobra.Command{
|
||||
Use: "serve",
|
||||
Short: "Start the HTTP server",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// TODO: implement server
|
||||
Short: "Start API and admin dashboard HTTP servers",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
cmd.Printf("API: http://%s\n", cfg.APIAddr())
|
||||
cmd.Printf("Admin: http://%s\n", cfg.AdminAddr())
|
||||
|
||||
if err := server.Run(ctx, cfg); err != nil {
|
||||
return fmt.Errorf("server: %w", err)
|
||||
}
|
||||
cmd.Println("Server beendet.")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
{
|
||||
"host": "127.0.0.1",
|
||||
"port": 8080
|
||||
"api_port": 8080,
|
||||
"admin_port": 8081
|
||||
}
|
||||
|
||||
@ -8,15 +8,20 @@ import (
|
||||
|
||||
// Config is the application configuration loaded from JSON.
|
||||
type Config struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Host string `json:"host"`
|
||||
APIPort int `json:"api_port"`
|
||||
AdminPort int `json:"admin_port"`
|
||||
|
||||
// Port is deprecated; mapped to APIPort when api_port is unset.
|
||||
Port int `json:"port"`
|
||||
}
|
||||
|
||||
// Default returns sensible defaults when no config file is used.
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
Host: "127.0.0.1",
|
||||
Port: 8080,
|
||||
Host: "127.0.0.1",
|
||||
APIPort: 8080,
|
||||
AdminPort: 8081,
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,5 +37,20 @@ func Load(path string) (*Config, error) {
|
||||
return nil, fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
|
||||
cfg.applyLegacyPort()
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) applyLegacyPort() {
|
||||
if c.Port != 0 && c.APIPort == 8080 {
|
||||
c.APIPort = c.Port
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) APIAddr() string {
|
||||
return fmt.Sprintf("%s:%d", c.Host, c.APIPort)
|
||||
}
|
||||
|
||||
func (c *Config) AdminAddr() string {
|
||||
return fmt.Sprintf("%s:%d", c.Host, c.AdminPort)
|
||||
}
|
||||
|
||||
27
internal/server/admin/admin.go
Normal file
27
internal/server/admin/admin.go
Normal file
@ -0,0 +1,27 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
//go:embed static
|
||||
var staticFS embed.FS
|
||||
|
||||
// NewHandler returns the admin dashboard HTTP handler.
|
||||
func NewHandler(apiBaseURL string) http.Handler {
|
||||
sub, err := fs.Sub(staticFS, "static")
|
||||
if err != nil {
|
||||
panic("admin static fs: " + err.Error())
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /config.json", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"api_base": apiBaseURL})
|
||||
})
|
||||
mux.Handle("/", http.FileServer(http.FS(sub)))
|
||||
return mux
|
||||
}
|
||||
200
internal/server/admin/static/index.html
Normal file
200
internal/server/admin/static/index.html
Normal file
@ -0,0 +1,200 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Printer Backend — Admin</title>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f1419;
|
||||
--surface: #1a2332;
|
||||
--border: #2d3a4d;
|
||||
--text: #e7ecf3;
|
||||
--muted: #8b9cb3;
|
||||
--accent: #3b82f6;
|
||||
--ok: #22c55e;
|
||||
--err: #ef4444;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.layout {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem 1.5rem;
|
||||
}
|
||||
header {
|
||||
margin-bottom: 2rem;
|
||||
padding-bottom: 1.5rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
header h1 { font-size: 1.5rem; font-weight: 600; }
|
||||
header p { color: var(--muted); margin-top: 0.25rem; font-size: 0.9rem; }
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
}
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
.card h2 {
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--muted);
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.status-dot {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
margin-right: 0.5rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.status-dot.ok { background: var(--ok); }
|
||||
.status-dot.err { background: var(--err); }
|
||||
.status-dot.pending { background: var(--muted); animation: pulse 1.2s ease-in-out infinite; }
|
||||
@keyframes pulse { 50% { opacity: 0.4; } }
|
||||
.value { font-size: 1.1rem; font-weight: 500; }
|
||||
.muted { color: var(--muted); font-size: 0.85rem; margin-top: 0.5rem; }
|
||||
button {
|
||||
margin-top: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { filter: brightness(1.1); }
|
||||
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
input {
|
||||
width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--text);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
label { font-size: 0.8rem; color: var(--muted); }
|
||||
pre {
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.75rem;
|
||||
background: var(--bg);
|
||||
border-radius: 6px;
|
||||
font-size: 0.75rem;
|
||||
overflow-x: auto;
|
||||
color: var(--muted);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout" x-data="dashboard()" x-init="init()">
|
||||
<header>
|
||||
<h1>Printer Backend</h1>
|
||||
<p>Admin-Dashboard</p>
|
||||
</header>
|
||||
|
||||
<div class="grid">
|
||||
<section class="card">
|
||||
<h2>API-Status</h2>
|
||||
<p class="value">
|
||||
<span class="status-dot" :class="apiStatusClass"></span>
|
||||
<span x-text="apiStatusLabel"></span>
|
||||
</p>
|
||||
<p class="muted" x-show="apiCheckedAt" x-text="'Zuletzt geprüft: ' + apiCheckedAt"></p>
|
||||
<button type="button" @click="checkAPI()" :disabled="apiLoading">
|
||||
<span x-text="apiLoading ? 'Prüfe…' : 'API erneut prüfen'"></span>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>API-Basis-URL</h2>
|
||||
<label for="api-base">Für Health-Check (gleicher Host, API-Port)</label>
|
||||
<input id="api-base" type="url" x-model="apiBase" @change="checkAPI()" placeholder="http://127.0.0.1:8080">
|
||||
<pre x-show="apiResponse" x-text="apiResponse"></pre>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>System</h2>
|
||||
<p class="value" x-text="now"></p>
|
||||
<p class="muted">Lokale Uhrzeit (Browser)</p>
|
||||
<button type="button" @click="refreshClock()">Uhr aktualisieren</button>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function dashboard() {
|
||||
return {
|
||||
apiBase: '',
|
||||
apiLoading: false,
|
||||
apiOk: null,
|
||||
apiResponse: '',
|
||||
apiCheckedAt: '',
|
||||
now: '',
|
||||
|
||||
get apiStatusClass() {
|
||||
if (this.apiOk === null) return 'pending';
|
||||
return this.apiOk ? 'ok' : 'err';
|
||||
},
|
||||
get apiStatusLabel() {
|
||||
if (this.apiOk === null) return 'Noch nicht geprüft';
|
||||
return this.apiOk ? 'API erreichbar' : 'API nicht erreichbar';
|
||||
},
|
||||
|
||||
async init() {
|
||||
try {
|
||||
const res = await fetch('/config.json');
|
||||
if (res.ok) {
|
||||
const cfg = await res.json();
|
||||
this.apiBase = cfg.api_base || this.apiBase;
|
||||
}
|
||||
} catch (_) { /* fallback below */ }
|
||||
if (!this.apiBase) {
|
||||
this.apiBase = 'http://127.0.0.1:8080';
|
||||
}
|
||||
this.refreshClock();
|
||||
this.checkAPI();
|
||||
setInterval(() => this.refreshClock(), 1000);
|
||||
},
|
||||
|
||||
refreshClock() {
|
||||
this.now = new Date().toLocaleString('de-DE');
|
||||
},
|
||||
|
||||
async checkAPI() {
|
||||
this.apiLoading = true;
|
||||
this.apiResponse = '';
|
||||
try {
|
||||
const res = await fetch(`${this.apiBase.replace(/\/$/, '')}/health`);
|
||||
const body = await res.json();
|
||||
this.apiOk = res.ok;
|
||||
this.apiResponse = JSON.stringify(body, null, 2);
|
||||
} catch (e) {
|
||||
this.apiOk = false;
|
||||
this.apiResponse = String(e.message || e);
|
||||
} finally {
|
||||
this.apiLoading = false;
|
||||
this.apiCheckedAt = new Date().toLocaleTimeString('de-DE');
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
27
internal/server/api/api.go
Normal file
27
internal/server/api/api.go
Normal file
@ -0,0 +1,27 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// NewHandler returns the API HTTP handler (routes under /).
|
||||
func NewHandler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health", health)
|
||||
mux.HandleFunc("GET /", root)
|
||||
return mux
|
||||
}
|
||||
|
||||
func health(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func root(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"service": "printer-backend-api",
|
||||
"message": "API placeholder — endpoints folgen",
|
||||
})
|
||||
}
|
||||
68
internal/server/server.go
Normal file
68
internal/server/server.go
Normal file
@ -0,0 +1,68 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"printer.backend/internal/config"
|
||||
"printer.backend/internal/server/admin"
|
||||
"printer.backend/internal/server/api"
|
||||
)
|
||||
|
||||
// Run starts the API and admin HTTP servers and blocks until ctx is cancelled.
|
||||
func Run(ctx context.Context, cfg *config.Config) error {
|
||||
apiSrv := &http.Server{
|
||||
Addr: cfg.APIAddr(),
|
||||
Handler: api.NewHandler(),
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
}
|
||||
apiBase := "http://" + cfg.APIAddr()
|
||||
adminSrv := &http.Server{
|
||||
Addr: cfg.AdminAddr(),
|
||||
Handler: admin.NewHandler(apiBase),
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, 2)
|
||||
|
||||
start := func(name string, srv *http.Server) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
log.Printf("%s listening on http://%s", name, srv.Addr)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errCh <- fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
start("API", apiSrv)
|
||||
start("Admin", adminSrv)
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case err := <-errCh:
|
||||
return err
|
||||
}
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var shutdownErr error
|
||||
for _, srv := range []*http.Server{apiSrv, adminSrv} {
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
shutdownErr = errors.Join(shutdownErr, err)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return shutdownErr
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user