summaryrefslogtreecommitdiffstats
path: root/main.go
blob: 764c8be8b4a871d6f95a04525201ad02997edd39 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"strings"

	"wg-portal/internal"
)

// APIResponse represents a standard API response structure
type APIResponse struct {
	Success bool   `json:"success"`
	Data    any    `json:"data,omitempty"`
	Error   string `json:"error,omitempty"`
}

// Server encapsulates our HTTP server
type Server struct {
	mux       *http.ServeMux
	templates *template.Template
	config    *internal.Config
}

// NewServer creates a new server instance
func NewServer(config *internal.Config) (*Server, error) {
	// Parse templates
	templates, err := template.ParseFiles("templates/index.html")
	if err != nil {
		return nil, fmt.Errorf("failed to parse templates: %w", err)
	}

	s := &Server{
		mux:       http.NewServeMux(),
		templates: templates,
		config:    config,
	}
	s.setupRoutes()
	return s, nil
}

// setupRoutes configures all HTTP routes
func (s *Server) setupRoutes() {
	// Serve static files
	s.mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))

	// Main page
	s.mux.HandleFunc("/", s.handleHome)

	// API endpoints
	s.mux.HandleFunc("/api/connections", s.handleConnectionsAPI)
	s.mux.HandleFunc("/api/connections/toggle", s.handleToggleAPI)
	s.mux.HandleFunc("/api/status", s.handleStatusAPI)
}

// handleHome serves the main HTML page
func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	templateData := map[string]any{
		"Title": s.config.Server.Title,
	}
	if err := s.templates.ExecuteTemplate(w, "index.html", templateData); err != nil {
		log.Printf("Error rendering template: %v", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
	}
}

// handleConnectionsAPI returns connection data as JSON
func (s *Server) handleConnectionsAPI(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		s.sendErrorResponse(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	connections, err := internal.GetConnections()
	if err != nil {
		log.Printf("Error getting connections: %v", err)
		s.sendErrorResponse(w, fmt.Sprintf("%v", err), http.StatusInternalServerError)
		return
	}

	s.sendSuccessResponse(w, connections)
}

// handleToggleAPI handles connection toggle requests
func (s *Server) handleToggleAPI(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		s.sendErrorResponse(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req struct {
		Name string `json:"name"`
	}

	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		s.sendErrorResponse(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	if strings.TrimSpace(req.Name) == "" {
		s.sendErrorResponse(w, "Connection name is required", http.StatusBadRequest)
		return
	}

	output, err := internal.ToggleConnection(req.Name)
	if err != nil {
		log.Printf("Error toggling connection %s: %v (output: %s)", req.Name, err, string(output))
		s.sendErrorResponse(w, err.Error(), http.StatusInternalServerError)
		return
	}

	response := map[string]any{
		"message": fmt.Sprintf("Connection %s toggled successfully", req.Name),
		"output":  string(output),
	}

	s.sendSuccessResponse(w, response)
}

// handleStatusAPI returns WireGuard status information
func (s *Server) handleStatusAPI(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		s.sendErrorResponse(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	status, err := internal.GetStatus()
	if err != nil {
		log.Printf("Error getting status: %v", err)
		s.sendErrorResponse(w, fmt.Sprintf("%v", err), http.StatusInternalServerError)
		return
	}

	response := map[string]any{
		"status": status,
	}

	s.sendSuccessResponse(w, response)
}

// sendSuccessResponse sends a JSON success response
func (*Server) sendSuccessResponse(w http.ResponseWriter, data any) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(APIResponse{
		Success: true,
		Data:    data,
	})
}

// sendErrorResponse sends a JSON error response
func (*Server) sendErrorResponse(w http.ResponseWriter, message string, statusCode int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	_ = json.NewEncoder(w).Encode(APIResponse{
		Success: false,
		Error:   message,
	})
}

// Start starts the HTTP server
func (s *Server) Start() error {
	addr := s.config.GetAddress()
	log.Printf("%s starting on http://%s\n", s.config.Server.Title, addr)
	return http.ListenAndServe(addr, s.mux)
}

func main() {
	// Load configuration
	config, err := internal.LoadConfig("config.yaml")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	server, err := NewServer(config)
	if err != nil {
		log.Fatalf("Failed to create server: %v", err)
	}

	if err := server.Start(); err != nil {
		log.Fatalf("Server failed to start: %v", err)
	}
}