generated from akmamun/gin-boilerplate
/
create_api.go
36 lines (30 loc) · 928 Bytes
/
create_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package controllers
import (
"github.com/akmamun/gin-boilerplate-examples/infra/database"
"github.com/akmamun/gin-boilerplate-examples/infra/logger"
"github.com/akmamun/gin-boilerplate-examples/models"
"github.com/gin-gonic/gin"
"net/http"
)
type ExampleController struct{}
func (ctrl *ExampleController) CreateExample(ctx *gin.Context) {
example := new(models.Example)
err := ctx.ShouldBindJSON(&example)
if err != nil {
logger.Errorf("error: %v", err)
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err = database.DB.Create(&example).Error
if err != nil {
logger.Errorf("error: %v", err)
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, &example)
}
func (ctrl *ExampleController) GetExampleData(ctx *gin.Context) {
var examples []models.Example
database.DB.Find(&examples)
ctx.JSON(http.StatusOK, gin.H{"data": examples})
}