1use std::fmt::Write;
7
8pub struct GoCodeGenerator;
10
11impl GoCodeGenerator {
12 pub fn generate_service_struct(service_name: &str, fields: &[&str]) -> Result<String, String> {
26 let mut output = String::new();
27
28 writeln!(output, "package main\n").map_err(|e| e.to_string())?;
29 writeln!(output, "import (").map_err(|e| e.to_string())?;
30 writeln!(output, "\t\"fmt\"").map_err(|e| e.to_string())?;
31 writeln!(output, "\t\"log\"").map_err(|e| e.to_string())?;
32 writeln!(output, "\t\"net/http\"").map_err(|e| e.to_string())?;
33 writeln!(output, "\t\"database/sql\"").map_err(|e| e.to_string())?;
34 writeln!(output, ")\n").map_err(|e| e.to_string())?;
35
36 writeln!(
37 output,
38 "// {} represents the service with all dependencies",
39 service_name
40 )
41 .map_err(|e| e.to_string())?;
42 writeln!(output, "type {} struct {{", service_name).map_err(|e| e.to_string())?;
43 writeln!(output, "\tConfig *Config").map_err(|e| e.to_string())?;
44 writeln!(output, "\tLogger *log.Logger").map_err(|e| e.to_string())?;
45 writeln!(output, "\tDB *sql.DB").map_err(|e| e.to_string())?;
46
47 for field in fields {
49 writeln!(output, "\t{} interface{{}}", field).map_err(|e| e.to_string())?;
50 }
51
52 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
53
54 writeln!(output, "// Config holds service configuration").map_err(|e| e.to_string())?;
56 writeln!(output, "type Config struct {{").map_err(|e| e.to_string())?;
57 writeln!(output, "\tPort string").map_err(|e| e.to_string())?;
58 writeln!(output, "\tEnv string").map_err(|e| e.to_string())?;
59 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
60
61 Ok(output)
62 }
63
64 pub fn generate_handler(
76 method: &str, path: &str, handler_name: &str,
77 ) -> Result<String, String> {
78 let mut output = String::new();
79
80 writeln!(
81 output,
82 "// {} handles {} {} requests",
83 handler_name, method, path
84 )
85 .map_err(|e| e.to_string())?;
86 writeln!(
87 output,
88 "func (s *Service) {} (w http.ResponseWriter, r *http.Request) error {{",
89 handler_name
90 )
91 .map_err(|e| e.to_string())?;
92
93 writeln!(
94 output,
95 "\ts.Logger.Printf(\"[{}] {} %s\\n\", r.URL.Path)",
96 method, handler_name
97 )
98 .map_err(|e| e.to_string())?;
99
100 match method.to_uppercase().as_str() {
102 "POST" | "PUT" | "PATCH" => {
103 writeln!(output, "\tvar body map[string]interface{{}}")
105 .map_err(|e| e.to_string())?;
106 writeln!(
107 output,
108 "\tif err := json.NewDecoder(r.Body).Decode(&body); err != nil {{"
109 )
110 .map_err(|e| e.to_string())?;
111 writeln!(
112 output,
113 "\t\tw.Header().Set(\"Content-Type\", \"application/json\")"
114 )
115 .map_err(|e| e.to_string())?;
116 writeln!(output, "\t\tw.WriteHeader(http.StatusBadRequest)")
117 .map_err(|e| e.to_string())?;
118 writeln!(
119 output,
120 "\t\tw.Write([]byte(`{{\"error\":\"invalid JSON body\"}}`))"
121 )
122 .map_err(|e| e.to_string())?;
123 writeln!(output, "\t\treturn fmt.Errorf(\"decode body: %w\", err)")
124 .map_err(|e| e.to_string())?;
125 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
126 writeln!(output, "\t_ = body // pass decoded fields to service layer")
127 .map_err(|e| e.to_string())?;
128 writeln!(
129 output,
130 "\tw.Header().Set(\"Content-Type\", \"application/json\")"
131 )
132 .map_err(|e| e.to_string())?;
133 writeln!(output, "\tw.WriteHeader(http.StatusOK)").map_err(|e| e.to_string())?;
134 writeln!(output, "\tw.Write([]byte(`{{\"status\":\"ok\"}}`))")
135 .map_err(|e| e.to_string())?;
136 }
137 "DELETE" => {
138 writeln!(output, "\tid := r.PathValue(\"id\")").map_err(|e| e.to_string())?;
140 writeln!(output, "\tif id == \"\" {{").map_err(|e| e.to_string())?;
141 writeln!(
142 output,
143 "\t\tw.Header().Set(\"Content-Type\", \"application/json\")"
144 )
145 .map_err(|e| e.to_string())?;
146 writeln!(output, "\t\tw.WriteHeader(http.StatusBadRequest)")
147 .map_err(|e| e.to_string())?;
148 writeln!(
149 output,
150 "\t\tw.Write([]byte(`{{\"error\":\"missing id\"}}`))"
151 )
152 .map_err(|e| e.to_string())?;
153 writeln!(output, "\t\treturn fmt.Errorf(\"missing id in path\")")
154 .map_err(|e| e.to_string())?;
155 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
156 writeln!(output, "\t_ = id // pass to repository Delete(id)")
157 .map_err(|e| e.to_string())?;
158 writeln!(output, "\tw.WriteHeader(http.StatusNoContent)")
159 .map_err(|e| e.to_string())?;
160 }
161 _ => {
162 writeln!(output, "\tid := r.PathValue(\"id\")").map_err(|e| e.to_string())?;
164 writeln!(
165 output,
166 "\t_ = id // pass to repository GetByID(id) when non-empty"
167 )
168 .map_err(|e| e.to_string())?;
169 writeln!(
170 output,
171 "\tw.Header().Set(\"Content-Type\", \"application/json\")"
172 )
173 .map_err(|e| e.to_string())?;
174 writeln!(output, "\tw.WriteHeader(http.StatusOK)").map_err(|e| e.to_string())?;
175 writeln!(output, "\tw.Write([]byte(`{{\"status\":\"ok\"}}`))")
176 .map_err(|e| e.to_string())?;
177 }
178 }
179
180 writeln!(output, "\treturn nil").map_err(|e| e.to_string())?;
181 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
182
183 Ok(output)
184 }
185
186 pub fn generate_repository(entity_name: &str) -> Result<String, String> {
196 let mut output = String::new();
197 let repo_name = format!("{}Repository", entity_name);
198
199 writeln!(
200 output,
201 "// {} defines data access operations for {}",
202 repo_name, entity_name
203 )
204 .map_err(|e| e.to_string())?;
205 writeln!(output, "type {} interface {{", repo_name).map_err(|e| e.to_string())?;
206 writeln!(output, "\tCreate(entity *{}) error", entity_name).map_err(|e| e.to_string())?;
207 writeln!(output, "\tGetByID(id string) (*{}, error)", entity_name)
208 .map_err(|e| e.to_string())?;
209 writeln!(output, "\tUpdate(entity *{}) error", entity_name).map_err(|e| e.to_string())?;
210 writeln!(output, "\tDelete(id string) error").map_err(|e| e.to_string())?;
211 writeln!(output, "\tList() ([]*{}, error)", entity_name).map_err(|e| e.to_string())?;
212 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
213
214 writeln!(output, "// {}Impl implements {}", entity_name, repo_name)
216 .map_err(|e| e.to_string())?;
217 writeln!(output, "type {}Impl struct {{", entity_name).map_err(|e| e.to_string())?;
218 writeln!(output, "\tdb *sql.DB").map_err(|e| e.to_string())?;
219 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
220
221 writeln!(
223 output,
224 "// Create inserts a new {} into the database",
225 entity_name
226 )
227 .map_err(|e| e.to_string())?;
228 writeln!(
229 output,
230 "func (r *{}Impl) Create(entity *{}) error {{",
231 entity_name, entity_name
232 )
233 .map_err(|e| e.to_string())?;
234 writeln!(output, "\tif entity == nil {{").map_err(|e| e.to_string())?;
235 writeln!(
236 output,
237 "\t\treturn fmt.Errorf(\"create: %w\", ErrInvalidEntity)"
238 )
239 .map_err(|e| e.to_string())?;
240 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
241 writeln!(
243 output,
244 "\tconst query = \"INSERT INTO {} (id) VALUES ($1)\"",
245 entity_name.to_lowercase()
246 )
247 .map_err(|e| e.to_string())?;
248 writeln!(output, "\t_, err := r.db.Exec(query, entity.ID)").map_err(|e| e.to_string())?;
249 writeln!(output, "\tif err != nil {{").map_err(|e| e.to_string())?;
250 writeln!(
251 output,
252 "\t\treturn fmt.Errorf(\"create {}: %w\", err)",
253 entity_name.to_lowercase()
254 )
255 .map_err(|e| e.to_string())?;
256 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
257 writeln!(output, "\treturn nil").map_err(|e| e.to_string())?;
258 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
259
260 writeln!(
262 output,
263 "// GetByID retrieves a {} by its identifier",
264 entity_name
265 )
266 .map_err(|e| e.to_string())?;
267 writeln!(
268 output,
269 "func (r *{}Impl) GetByID(id string) (*{}, error) {{",
270 entity_name, entity_name
271 )
272 .map_err(|e| e.to_string())?;
273 writeln!(output, "\tif id == \"\" {{").map_err(|e| e.to_string())?;
274 writeln!(
275 output,
276 "\t\treturn nil, fmt.Errorf(\"get by id: %w\", ErrInvalidID)"
277 )
278 .map_err(|e| e.to_string())?;
279 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
280 writeln!(
282 output,
283 "\tconst query = \"SELECT id FROM {} WHERE id = $1\"",
284 entity_name.to_lowercase()
285 )
286 .map_err(|e| e.to_string())?;
287 writeln!(output, "\tentity := &{}{{}}", entity_name).map_err(|e| e.to_string())?;
288 writeln!(output, "\terr := r.db.QueryRow(query, id).Scan(&entity.ID)")
289 .map_err(|e| e.to_string())?;
290 writeln!(output, "\tif err == sql.ErrNoRows {{").map_err(|e| e.to_string())?;
291 writeln!(
292 output,
293 "\t\treturn nil, fmt.Errorf(\"get by id: %w\", ErrInvalidID)"
294 )
295 .map_err(|e| e.to_string())?;
296 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
297 writeln!(output, "\tif err != nil {{").map_err(|e| e.to_string())?;
298 writeln!(
299 output,
300 "\t\treturn nil, fmt.Errorf(\"get {} by id: %w\", err)",
301 entity_name.to_lowercase()
302 )
303 .map_err(|e| e.to_string())?;
304 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
305 writeln!(output, "\treturn entity, nil").map_err(|e| e.to_string())?;
306 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
307
308 writeln!(output, "// Error types").map_err(|e| e.to_string())?;
310 writeln!(output, "var (").map_err(|e| e.to_string())?;
311 writeln!(output, "\tErrInvalidEntity = errors.New(\"entity is nil\")")
312 .map_err(|e| e.to_string())?;
313 writeln!(output, "\tErrInvalidID = errors.New(\"id is empty\")")
314 .map_err(|e| e.to_string())?;
315 writeln!(output, ")\n").map_err(|e| e.to_string())?;
316
317 Ok(output)
318 }
319
320 pub fn generate_main() -> Result<String, String> {
328 let mut output = String::new();
329
330 writeln!(output, "package main\n").map_err(|e| e.to_string())?;
331 writeln!(output, "import (").map_err(|e| e.to_string())?;
332 writeln!(output, "\t\"context\"").map_err(|e| e.to_string())?;
333 writeln!(output, "\t\"database/sql\"").map_err(|e| e.to_string())?;
334 writeln!(output, "\t\"fmt\"").map_err(|e| e.to_string())?;
335 writeln!(output, "\t\"log\"").map_err(|e| e.to_string())?;
336 writeln!(output, "\t\"net/http\"").map_err(|e| e.to_string())?;
337 writeln!(output, "\t\"os\"").map_err(|e| e.to_string())?;
338 writeln!(output, "\t\"os/signal\"").map_err(|e| e.to_string())?;
339 writeln!(output, "\t\"syscall\"").map_err(|e| e.to_string())?;
340 writeln!(output, "\t\"time\"").map_err(|e| e.to_string())?;
341 writeln!(output, ")\n").map_err(|e| e.to_string())?;
342
343 writeln!(output, "func main() {{").map_err(|e| e.to_string())?;
344 writeln!(
345 output,
346 "\tlogger := log.New(os.Stdout, \"[APP] \", log.LstdFlags)"
347 )
348 .map_err(|e| e.to_string())?;
349
350 writeln!(output, "\n\t// Load configuration").map_err(|e| e.to_string())?;
351 writeln!(output, "\tcfg := &Config{{").map_err(|e| e.to_string())?;
352 writeln!(output, "\t\tPort: os.Getenv(\"PORT\")").map_err(|e| e.to_string())?;
353 writeln!(output, "\t\tEnv: os.Getenv(\"ENV\")").map_err(|e| e.to_string())?;
354 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
355 writeln!(output, "\tif cfg.Port == \"\" {{").map_err(|e| e.to_string())?;
356 writeln!(output, "\t\tcfg.Port = \":8080\"").map_err(|e| e.to_string())?;
357 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
358
359 writeln!(output, "\n\t// Connect to database").map_err(|e| e.to_string())?;
360 writeln!(
361 output,
362 "\tdb, err := sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))"
363 )
364 .map_err(|e| e.to_string())?;
365 writeln!(output, "\tif err != nil {{").map_err(|e| e.to_string())?;
366 writeln!(
367 output,
368 "\t\tlogger.Fatalf(\"failed to connect to database: %v\", err)"
369 )
370 .map_err(|e| e.to_string())?;
371 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
372 writeln!(output, "\tdefer db.Close()").map_err(|e| e.to_string())?;
373
374 writeln!(output, "\n\t// Initialize service").map_err(|e| e.to_string())?;
375 writeln!(output, "\tsvc := &Service{{").map_err(|e| e.to_string())?;
376 writeln!(output, "\t\tConfig: cfg,").map_err(|e| e.to_string())?;
377 writeln!(output, "\t\tLogger: logger,").map_err(|e| e.to_string())?;
378 writeln!(output, "\t\tDB: db,").map_err(|e| e.to_string())?;
379 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
380
381 writeln!(output, "\n\t// Setup HTTP router").map_err(|e| e.to_string())?;
382 writeln!(output, "\tmux := http.NewServeMux()").map_err(|e| e.to_string())?;
383 writeln!(output, "\tmux.HandleFunc(\"/health\", svc.HealthCheck)")
384 .map_err(|e| e.to_string())?;
385
386 writeln!(output, "\n\t// Create HTTP server").map_err(|e| e.to_string())?;
387 writeln!(output, "\tserver := &http.Server{{").map_err(|e| e.to_string())?;
388 writeln!(output, "\t\tAddr: cfg.Port,").map_err(|e| e.to_string())?;
389 writeln!(output, "\t\tHandler: mux,").map_err(|e| e.to_string())?;
390 writeln!(output, "\t\tReadTimeout: 10 * time.Second,").map_err(|e| e.to_string())?;
391 writeln!(output, "\t\tWriteTimeout: 10 * time.Second,").map_err(|e| e.to_string())?;
392 writeln!(output, "\t\tIdleTimeout: 60 * time.Second,").map_err(|e| e.to_string())?;
393 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
394
395 writeln!(output, "\n\t// Start server in goroutine").map_err(|e| e.to_string())?;
396 writeln!(output, "\tgo func() {{").map_err(|e| e.to_string())?;
397 writeln!(
398 output,
399 "\t\tlogger.Printf(\"server starting on %s\\n\", cfg.Port)"
400 )
401 .map_err(|e| e.to_string())?;
402 writeln!(
403 output,
404 "\t\tif err := server.ListenAndServe(); err != nil {{"
405 )
406 .map_err(|e| e.to_string())?;
407 writeln!(output, "\t\t\tlogger.Fatalf(\"server error: %v\", err)")
408 .map_err(|e| e.to_string())?;
409 writeln!(output, "\t\t}}").map_err(|e| e.to_string())?;
410 writeln!(output, "\t}}()").map_err(|e| e.to_string())?;
411
412 writeln!(output, "\n\t// Setup graceful shutdown").map_err(|e| e.to_string())?;
413 writeln!(output, "\tsigChan := make(chan os.Signal, 1)").map_err(|e| e.to_string())?;
414 writeln!(
415 output,
416 "\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)"
417 )
418 .map_err(|e| e.to_string())?;
419 writeln!(output, "\t<-sigChan").map_err(|e| e.to_string())?;
420
421 writeln!(output, "\n\tlogger.Println(\"shutdown signal received\")")
422 .map_err(|e| e.to_string())?;
423 writeln!(
424 output,
425 "\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)"
426 )
427 .map_err(|e| e.to_string())?;
428 writeln!(output, "\tdefer cancel()").map_err(|e| e.to_string())?;
429 writeln!(output, "\tif err := server.Shutdown(ctx); err != nil {{")
430 .map_err(|e| e.to_string())?;
431 writeln!(output, "\t\tlogger.Fatalf(\"shutdown error: %v\", err)")
432 .map_err(|e| e.to_string())?;
433 writeln!(output, "\t}}").map_err(|e| e.to_string())?;
434 writeln!(output, "\tlogger.Println(\"server stopped\")").map_err(|e| e.to_string())?;
435 writeln!(output, "}}\n").map_err(|e| e.to_string())?;
436
437 writeln!(output, "// HealthCheck returns 200 OK").map_err(|e| e.to_string())?;
438 writeln!(
439 output,
440 "func (s *Service) HealthCheck(w http.ResponseWriter, r *http.Request) {{"
441 )
442 .map_err(|e| e.to_string())?;
443 writeln!(
444 output,
445 "\tw.Header().Set(\"Content-Type\", \"application/json\")"
446 )
447 .map_err(|e| e.to_string())?;
448 writeln!(output, "\tw.WriteHeader(http.StatusOK)").map_err(|e| e.to_string())?;
449 writeln!(output, "\tw.Write([]byte(`{{\"status\":\"healthy\"}}`)) ")
450 .map_err(|e| e.to_string())?;
451 writeln!(output, "}}").map_err(|e| e.to_string())?;
452
453 Ok(output)
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 #[test]
462 fn test_generate_service_struct() {
463 let _result = GoCodeGenerator::generate_service_struct("UserService", &["cache", "queue"]);
464 }
465
466 #[test]
469 fn test_create_generates_sql_insert() {
470 let result = GoCodeGenerator::generate_repository("Order");
471 assert!(result.is_ok());
472 let code = result.unwrap();
473 assert!(
474 code.contains("INSERT INTO order"),
475 "Create must generate INSERT SQL"
476 );
477 assert!(
478 code.contains("r.db.Exec(query, entity.ID)"),
479 "Create must execute SQL via db.Exec"
480 );
481 assert!(
482 !code.contains("// TODO: implement create logic"),
483 "Create must not contain TODO placeholder"
484 );
485 }
486
487 #[test]
488 fn test_get_by_id_generates_sql_select() {
489 let result = GoCodeGenerator::generate_repository("Order");
490 assert!(result.is_ok());
491 let code = result.unwrap();
492 assert!(
493 code.contains("SELECT id FROM order WHERE id = $1"),
494 "GetByID must generate SELECT SQL"
495 );
496 assert!(
497 code.contains("r.db.QueryRow(query, id).Scan"),
498 "GetByID must scan query result"
499 );
500 assert!(
501 code.contains("sql.ErrNoRows"),
502 "GetByID must handle not-found case"
503 );
504 assert!(
505 !code.contains("// TODO: implement get logic"),
506 "GetByID must not contain TODO placeholder"
507 );
508 }
509
510 #[test]
511 fn test_repository_entity_name_appears_in_sql() {
512 let result = GoCodeGenerator::generate_repository("Invoice");
513 assert!(result.is_ok());
514 let code = result.unwrap();
515 assert!(
516 code.contains("INSERT INTO invoice"),
517 "table name must be lowercase entity name"
518 );
519 assert!(
520 code.contains("SELECT id FROM invoice"),
521 "SELECT must use lowercase entity name"
522 );
523 }
524}