diff --git a/code/mytodo/data/db.go b/code/mytodo/data/db.go new file mode 100644 index 0000000000000000000000000000000000000000..38dc2faef5d7990531bb94b4644225ae37a3716f --- /dev/null +++ b/code/mytodo/data/db.go @@ -0,0 +1,6 @@ +package data + +import "gitlab.reutlingen-university.de/schmolli/todo/model" + +var Todos = []model.Todo{} +var NextId = 0 diff --git a/code/mytodo/handler/todo.go b/code/mytodo/handler/todo.go new file mode 100644 index 0000000000000000000000000000000000000000..cc106cae2abd8d170c1a66ed63d1bb996e1ab53c --- /dev/null +++ b/code/mytodo/handler/todo.go @@ -0,0 +1,42 @@ +package handler + +import ( + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + "gitlab.reutlingen-university.de/schmolli/todo/data" + "gitlab.reutlingen-university.de/schmolli/todo/model" +) + +func AddTodo(c *gin.Context) { + var todo model.Todo + if err := c.BindJSON(&todo); err != nil { + c.IndentedJSON(http.StatusBadRequest, fmt.Sprintf("{\"error message\" : \"%s\"}", err.Error())) + } + todo.ID = data.NextId + data.NextId++ + data.Todos = append(data.Todos, todo) + c.IndentedJSON(http.StatusCreated, todo) +} + +func GetTodos(c *gin.Context) { + c.IndentedJSON(http.StatusOK, data.Todos) +} + +func GetToDoByID(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.IndentedJSON(http.StatusBadRequest, gin.H{"message": "illegal id "}) + return + } + + for _, t := range data.Todos { + if t.ID == id { + c.IndentedJSON(http.StatusOK, t) + return + } + } + c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Todo not found"}) +} diff --git a/code/mytodo/main.go b/code/mytodo/main.go index b2016fe54fa679b34ebcae92d3606378e492f614..d2aa6ca7ade0fba0bf83c10448c273eda1f76297 100644 --- a/code/mytodo/main.go +++ b/code/mytodo/main.go @@ -1,17 +1,15 @@ package main import ( - "fmt" - "github.com/gin-gonic/gin" "gitlab.reutlingen-university.de/schmolli/todo/handler" - "gitlab.reutlingen-university.de/schmolli/todo/model" ) func main() { - todo := model.CreateTodo("Coden") - fmt.Println(todo.Description) r := gin.Default() - r.GET("/health", handler.Health) + r.GET("/mytodo/health", handler.Health) + r.GET("/mytodo/todos", handler.GetTodos) + r.GET("/mytodo/todos/:id", handler.GetToDoByID) + r.POST("/mytodo/todos", handler.AddTodo) r.Run(":10000") } diff --git a/code/mytodo/model/todo.go b/code/mytodo/model/todo.go index 4fd461da13d06b495fae5e800e4341c5e363951c..ce92ff0200b0247aaf26371a861b9eff99c4cbc1 100644 --- a/code/mytodo/model/todo.go +++ b/code/mytodo/model/todo.go @@ -1,11 +1,6 @@ package model type Todo struct { - Description string -} - -func CreateTodo(Description string) Todo { - var todo Todo - todo.Description = Description - return todo + ID int `json:"id"` + Description string `json:"description"` }