Skip to content
Snippets Groups Projects
Commit 85ab5576 authored by Martin Schmollinger's avatar Martin Schmollinger
Browse files

Simple REST API to Add and Read TODO items.

parent 6c62868b
No related branches found
No related tags found
No related merge requests found
package data
import "gitlab.reutlingen-university.de/schmolli/todo/model"
var Todos = []model.Todo{}
var NextId = 0
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"})
}
package main package main
import ( import (
"fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gitlab.reutlingen-university.de/schmolli/todo/handler" "gitlab.reutlingen-university.de/schmolli/todo/handler"
"gitlab.reutlingen-university.de/schmolli/todo/model"
) )
func main() { func main() {
todo := model.CreateTodo("Coden")
fmt.Println(todo.Description)
r := gin.Default() 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") r.Run(":10000")
} }
package model package model
type Todo struct { type Todo struct {
Description string ID int `json:"id"`
} Description string `json:"description"`
func CreateTodo(Description string) Todo {
var todo Todo
todo.Description = Description
return todo
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment