Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "context"
- "fmt"
- "html/template"
- "net/http"
- "github.com/jackc/pgx/v4/pgxpool"
- "github.com/labstack/echo/v4"
- )
- // User struct to hold the data fetched from database
- type User struct {
- ID int `json:"id"`
- Name string `json:"name"`
- City string `json:"city"`
- Salary int `json:"salary"`
- }
- // UserHandler handles the GET request for user data
- func UserHandler(db *pgxpool.Pool) echo.HandlerFunc {
- return func(c echo.Context) error {
- // Get user ID from the URL parameter
- userID := c.Param("id")
- // Query the database
- user, err := getUserByID(c.Request().Context(), db, userID)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("Error fetching user: %v", err))
- }
- if user == nil {
- return c.String(http.StatusNotFound, "User not found")
- }
- // Create HTML template
- tmpl := `
- <!DOCTYPE html>
- <html>
- <head>
- <title>User Details</title>
- <style>
- body {
- font-family: Arial, sans-serif;
- margin: 20px;
- }
- .user-card {
- border: 1px solid #ddd;
- border-radius: 5px;
- padding: 20px;
- max-width: 400px;
- }
- .field {
- margin-bottom: 10px;
- }
- .label {
- font-weight: bold;
- }
- </style>
- </head>
- <body>
- <div class="user-card">
- <h2>User Details</h2>
- <div class="field">
- <span class="label">ID:</span> {{.ID}}
- </div>
- <div class="field">
- <span class="label">Name:</span> {{.Name}}
- </div>
- <div class="field">
- <span class="label">City:</span> {{.City}}
- </div>
- <div class="field">
- <span class="label">Salary:</span> ${{.Salary}}
- </div>
- </div>
- </body>
- </html>
- `
- // Parse and execute the template
- t := template.Must(template.New("user").Parse(tmpl))
- return c.Render(http.StatusOK, t, user)
- }
- }
- // getUserByID fetches user data from the database
- func getUserByID(ctx context.Context, db *pgxpool.Pool, userID string) (*User, error) {
- var user User
- // SQL query to fetch user data
- query := `SELECT id, name, city, salary FROM users WHERE id = $1`
- // Execute the query
- row := db.QueryRow(ctx, query, userID)
- // Scan the result into the User struct
- err := row.Scan(&user.ID, &user.Name, &user.City, &user.Salary)
- if err != nil {
- // If no rows were found
- if err.Error() == "no rows in result set" {
- return nil, nil
- }
- return nil, err
- }
- return &user, nil
- }
- // Main function to set up Echo and routes
- func main() {
- // Initialize Echo
- e := echo.New()
- // Initialize database connection pool (using a placeholder function)
- db := initDB()
- defer db.Close()
- // Set up the renderer
- e.Renderer = &TemplateRenderer{}
- // Route to handle user GET requests
- e.GET("/user/:id", UserHandler(db))
- // Start the server
- e.Start(":8080")
- }
- // TemplateRenderer is a custom renderer for Echo
- type TemplateRenderer struct{}
- // Render implements the echo.Renderer interface
- func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
- if tmpl, ok := name.(*template.Template); ok {
- return tmpl.Execute(w, data)
- }
- return fmt.Errorf("template not found")
- }
- // Placeholder for database initialization
- func initDB() *pgxpool.Pool {
- // This would normally contain your database connection code
- // For example:
- // connStr := "postgres://username:password@localhost:5432/database_name"
- // db, err := pgxpool.Connect(context.Background(), connStr)
- // if err != nil {
- // panic(err)
- // }
- // return db
- // This is just a placeholder
- return nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement