Go structure

From UVOO Tech Wiki
Revision as of 00:03, 14 April 2024 by Busk (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
project/
│
├── cmd/
│   └── your_app/
│       └── main.go
│
├── internal/
│   ├── models/
│   │   ├── user.go
│   │   └── post.go
│   │   └── ...
│   │
│   ├── handlers/
│   │   ├── user_handler.go
│   │   └── post_handler.go
│   │   └── ...
│   │
│   └── routes/
│       ├── user_routes.go
│       └── post_routes.go
│       └── ...
│
└── go.mod
// main.go
package main

import (
    "project/internal/routes"
    "github.com/labstack/echo/v4"
)

func main() {
    e := echo.New()

    // Initialize routes
    routes.InitUserRoutes(e)
    routes.InitPostRoutes(e)
    routes.InitCommentRoutes(e)

    // Start the server
    e.Logger.Fatal(e.Start(":8080"))
}
go
Copy code
// internal/routes/user_routes.go
package routes

import (
    "github.com/labstack/echo/v4"
    "project/internal/handlers"
)

// InitUserRoutes initializes user routes
func InitUserRoutes(e *echo.Echo) {
    e.GET("/users", handlers.GetUsers)
    e.GET("/users/:id", handlers.GetUserByID)
    e.POST("/users", handlers.CreateUser)
    e.PUT("/users/:id", handlers.UpdateUser)
    e.DELETE("/users/:id", handlers.DeleteUser)
}
go
Copy code
// internal/handlers/user_handler.go
package handlers

import (
    "github.com/labstack/echo/v4"
    "net/http"
)

// GetUsers handles GET /users
func GetUsers(c echo.Context) error {
    // Get users from database and return response
    return c.String(http.StatusOK, "GetUsers handler")
}

// GetUserByID handles GET /users/:id
func GetUserByID(c echo.Context) error {
    // Get user by ID from database and return response
    return c.String(http.StatusOK, "GetUserByID handler")
}

// CreateUser handles POST /users
func CreateUser(c echo.Context) error {
    // Create user in database and return response
    return c.String(http.StatusCreated, "CreateUser handler")
}

// UpdateUser handles PUT /users/:id
func UpdateUser(c echo.Context) error {
    // Update user in database and return response
    return c.String(http.StatusOK, "UpdateUser handler")
}

// DeleteUser handles DELETE /users/:id
func DeleteUser(c echo.Context) error {
    // Delete user from database and return response
    return c.String(http.StatusOK, "DeleteUser handler")
}