Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "database/sql"
- "fmt"
- "net/http"
- "github.com/labstack/echo/v4"
- _ "github.com/lib/pq"
- )
- // User represents the user data structure
- type User struct {
- ID int
- Name string
- City string
- Salary float64
- }
- // getUserHandler handles GET requests to fetch user data by ID
- func getUserHandler(db *sql.DB) echo.HandlerFunc {
- return func(c echo.Context) error {
- // Get user ID from URL parameter
- id := c.Param("id")
- // Query the database
- var user User
- err := db.QueryRow("SELECT id, name, city, salary FROM users WHERE id = $1", id).
- Scan(&user.ID, &user.Name, &user.City, &user.Salary)
- if err == sql.ErrNoRows {
- return c.HTML(http.StatusNotFound, "<h1>User not found</h1>")
- }
- if err != nil {
- return c.HTML(http.StatusInternalServerError, "<h1>Error fetching user</h1>")
- }
- // Render basic HTML response
- html := fmt.Sprintf(`
- <!DOCTYPE html>
- <html>
- <head>
- <title>User Details</title>
- <style>
- body { font-family: Arial, sans-serif; margin: 40px; }
- .container { max-width: 600px; margin: 0 auto; }
- h1 { color: #333; }
- ul { list-style: none; padding: 0; }
- li { margin: 10px 0; }
- </style>
- </head>
- <body>
- <div class="container">
- <h1>User Details</h1>
- <ul>
- <li><strong>ID:</strong> %d</li>
- <li><strong>Name:</strong> %s</li>
- <li><strong>City:</strong> %s</li>
- <li><strong>Salary:</strong> $%.2f</li>
- </ul>
- </div>
- </body>
- </html>
- `, user.ID, user.Name, user.City, user.Salary)
- return c.HTML(http.StatusOK, html)
- }
- }
- // Example main function (for context, not required for the handler)
- func main() {
- // Assume db is an initialized *sql.DB connection to PostgreSQL
- var db *sql.DB // Replace with actual database connection
- e := echo.New()
- e.GET("/users/:id", getUserHandler(db))
- e.Logger.Fatal(e.Start(":8080"))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement