Creating a simple To-Do application in Go using the Echo framework and SQLite involves several steps. Below is a basic implementation that covers the essential features: adding, retrieving, updating, and deleting tasks.
Prerequisites
Make sure you have Go installed on your machine. You also need to install the Echo framework and the SQLite driver for Go. You can do this by running:
bash
go get github.com/labstack/echo/v4
go get github.com/mattn/go-sqlite3
Directory Structure
Create a directory for your project:
code
todo-app/
├── main.go
└── todo.db
main.go
Here’s a simple implementation of a To-Do application:
go
package main
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/mattn/go-sqlite3"
"database/sql"
"log"
"strconv"
)
// Task represents a to-do task
type Task struct {
ID int `json:"id"`
Name string `json:"name"`
Done bool `json:"done"`
}
var db *sql.DB
// Initialize the database
func initDB() {
var err error
db, err = sql.Open("sqlite3", "./todo.db")
if err != nil {
log.Fatal(err)
}
sqlStmt := `
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
done BOOLEAN NOT NULL DEFAULT 0
);
`
_, err = db.Exec(sqlStmt)
if err != nil {
log.Fatalf("%q: %s\n", err, sqlStmt)
return
}
}
// Get all tasks
func getTasks(c echo.Context) error {
rows, err := db.Query("SELECT id, name, done FROM tasks")
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
defer rows.Close()
var tasks []Task
for rows.Next() {
var task Task
if err := rows.Scan(&task.ID, &task.Name, &task.Done); err != nil {
return err
}
tasks = append(tasks, task)
}
return c.JSON(http.StatusOK, tasks)
}
// Create a new task
func createTask(c echo.Context) error {
task := Task{}
if err := c.Bind(&task); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
stmt, err := db.Prepare("INSERT INTO tasks(name, done) VALUES(?, ?)")
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
defer stmt.Close()
res, err := stmt.Exec(task.Name, task.Done)
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
id, err := res.LastInsertId()
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
task.ID = int(id)
return c.JSON(http.StatusCreated, task)
}
// Update a task
func updateTask(c echo.Context) error {
id := c.Param("id")
task := Task{}
if err := c.Bind(&task); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
stmt, err := db.Prepare("UPDATE tasks SET name = ?, done = ? WHERE id = ?")
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
defer stmt.Close()
_, err = stmt.Exec(task.Name, task.Done, id)
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
task.ID, _ = strconv.Atoi(id)
return c.JSON(http.StatusOK, task)
}
// Delete a task
func deleteTask(c echo.Context) error {
id := c.Param("id")
stmt, err := db.Prepare("DELETE FROM tasks WHERE id = ?")
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
defer stmt.Close()
_, err = stmt.Exec(id)
if err != nil {
return c.JSON(http.StatusInternalServerError, err.Error())
}
return c.NoContent(http.StatusNoContent)
}
func main() {
initDB()
e := echo.New()
e.GET("/tasks", getTasks)
e.POST("/tasks", createTask)
e.PUT("/tasks/:id", updateTask)
e.DELETE("/tasks/:id", deleteTask)
e.Logger.Fatal(e.Start(":8080"))
}
Running the Application
Save the above code in a file named main.go.
Open a terminal and navigate to the todo-app directory.
Run the application:
bash
go run main.go
Testing the API
You can use tools like curl or Postman to test the API.
This is a basic To-Do application using Go, Echo, and SQLite. You can expand upon this by adding features like user authentication, task categories, or due dates. Make sure to handle errors and edge cases in a production application.