Add get tasks endpoint (#29)

Closes #20

Reviewed-on: #29
This commit was merged in pull request #29.
This commit is contained in:
2025-05-13 10:36:24 +02:00
parent ec635ba8ff
commit 2c133e0d85
3 changed files with 101 additions and 12 deletions

View File

@@ -3,8 +3,8 @@ package main
import (
"context"
"embed"
"errors"
"log"
"net"
"net/http"
"os"
"strconv"
@@ -31,7 +31,10 @@ type ServerConfig struct {
// The port to listen on.
// Use an empty string to listen on a random port.
Port string
Addr string
// The port that is actually being listened on.
Port int
// The channel that gets signaled when the server has started.
Started chan bool
@@ -221,6 +224,16 @@ func createTask(c *gin.Context) {
c.IndentedJSON(http.StatusCreated, response)
}
func getTasks(c *gin.Context) {
response, err := db.GetTasks()
if err != nil {
log.Printf("Error getting tasks: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
return
}
c.JSON(http.StatusOK, &response)
}
/*
*
Initialises the database, and then starts the server.
@@ -237,21 +250,29 @@ func start(ctx context.Context, config *ServerConfig) {
router.POST("/api/user/:userId/goals", createUserGoal)
router.DELETE("/api/user/:userId/goal/:goalId", deleteUserGoal)
router.POST("/api/tasks", createTask)
router.GET("/api/tasks", getTasks)
srv := &http.Server{
Addr: ":" + config.Port,
Addr: config.Addr,
Handler: router.Handler(),
}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
l, err := net.Listen("tcp", srv.Addr)
if err != nil {
log.Fatalf("listen: %s\n", err)
}
config.Port = l.Addr().(*net.TCPAddr).Port
log.Printf("Running server on port %s\n", l.Addr().String())
if config.Started != nil {
config.Started <- true
}
if err := http.Serve(l, router.Handler()); err != nil {
log.Fatalf("listen: %s\n", err)
}
}()
log.Printf("Running server on port %s\n", config.Port)
if config.Started != nil {
config.Started <- true
}
<-ctx.Done()
log.Println("Shutting down")
if err := srv.Shutdown(context.Background()); err != nil {