Advertisement
Guest User

Simple Go-pgxpool page

a guest
May 14th, 2025
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 3.75 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "fmt"
  6.     "html/template"
  7.     "net/http"
  8.  
  9.     "github.com/jackc/pgx/v4/pgxpool"
  10.     "github.com/labstack/echo/v4"
  11. )
  12.  
  13. // User struct to hold the data fetched from database
  14. type User struct {
  15.     ID     int    `json:"id"`
  16.     Name   string `json:"name"`
  17.     City   string `json:"city"`
  18.     Salary int    `json:"salary"`
  19. }
  20.  
  21. // UserHandler handles the GET request for user data
  22. func UserHandler(db *pgxpool.Pool) echo.HandlerFunc {
  23.     return func(c echo.Context) error {
  24.         // Get user ID from the URL parameter
  25.         userID := c.Param("id")
  26.        
  27.         // Query the database
  28.         user, err := getUserByID(c.Request().Context(), db, userID)
  29.         if err != nil {
  30.             return c.String(http.StatusInternalServerError, fmt.Sprintf("Error fetching user: %v", err))
  31.         }
  32.        
  33.         if user == nil {
  34.             return c.String(http.StatusNotFound, "User not found")
  35.         }
  36.        
  37.         // Create HTML template
  38.         tmpl := `
  39. <!DOCTYPE html>
  40. <html>
  41. <head>
  42.     <title>User Details</title>
  43.     <style>
  44.         body {
  45.             font-family: Arial, sans-serif;
  46.             margin: 20px;
  47.         }
  48.         .user-card {
  49.             border: 1px solid #ddd;
  50.             border-radius: 5px;
  51.             padding: 20px;
  52.             max-width: 400px;
  53.         }
  54.         .field {
  55.             margin-bottom: 10px;
  56.         }
  57.         .label {
  58.             font-weight: bold;
  59.         }
  60.     </style>
  61. </head>
  62. <body>
  63.     <div class="user-card">
  64.         <h2>User Details</h2>
  65.         <div class="field">
  66.             <span class="label">ID:</span> {{.ID}}
  67.         </div>
  68.         <div class="field">
  69.             <span class="label">Name:</span> {{.Name}}
  70.         </div>
  71.         <div class="field">
  72.             <span class="label">City:</span> {{.City}}
  73.         </div>
  74.         <div class="field">
  75.             <span class="label">Salary:</span> ${{.Salary}}
  76.         </div>
  77.     </div>
  78. </body>
  79. </html>
  80. `
  81.        
  82.         // Parse and execute the template
  83.         t := template.Must(template.New("user").Parse(tmpl))
  84.         return c.Render(http.StatusOK, t, user)
  85.     }
  86. }
  87.  
  88. // getUserByID fetches user data from the database
  89. func getUserByID(ctx context.Context, db *pgxpool.Pool, userID string) (*User, error) {
  90.     var user User
  91.    
  92.     // SQL query to fetch user data
  93.     query := `SELECT id, name, city, salary FROM users WHERE id = $1`
  94.    
  95.     // Execute the query
  96.     row := db.QueryRow(ctx, query, userID)
  97.    
  98.     // Scan the result into the User struct
  99.     err := row.Scan(&user.ID, &user.Name, &user.City, &user.Salary)
  100.     if err != nil {
  101.         // If no rows were found
  102.         if err.Error() == "no rows in result set" {
  103.             return nil, nil
  104.         }
  105.         return nil, err
  106.     }
  107.    
  108.     return &user, nil
  109. }
  110.  
  111. // Main function to set up Echo and routes
  112. func main() {
  113.     // Initialize Echo
  114.     e := echo.New()
  115.    
  116.     // Initialize database connection pool (using a placeholder function)
  117.     db := initDB()
  118.     defer db.Close()
  119.    
  120.     // Set up the renderer
  121.     e.Renderer = &TemplateRenderer{}
  122.    
  123.     // Route to handle user GET requests
  124.     e.GET("/user/:id", UserHandler(db))
  125.    
  126.     // Start the server
  127.     e.Start(":8080")
  128. }
  129.  
  130. // TemplateRenderer is a custom renderer for Echo
  131. type TemplateRenderer struct{}
  132.  
  133. // Render implements the echo.Renderer interface
  134. func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
  135.     if tmpl, ok := name.(*template.Template); ok {
  136.         return tmpl.Execute(w, data)
  137.     }
  138.     return fmt.Errorf("template not found")
  139. }
  140.  
  141. // Placeholder for database initialization
  142. func initDB() *pgxpool.Pool {
  143.     // This would normally contain your database connection code
  144.     // For example:
  145.     // connStr := "postgres://username:password@localhost:5432/database_name"
  146.     // db, err := pgxpool.Connect(context.Background(), connStr)
  147.     // if err != nil {
  148.     //     panic(err)
  149.     // }
  150.     // return db
  151.    
  152.     // This is just a placeholder
  153.     return nil
  154. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement