/
ivvlb
/
FirstRESRAPIOnGo
Обзор
Документация
Войти
/
ivvlb
/
FirstRESRAPIOnGo
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
handler.go
115 строк
2 KB
ivvlb1202
I've done this project (owO)
01 янв 2025, 16:30
01 янв 2025, 16:30
0d14245
Код
Авторство
О чём код?
package main import ( "fmt" "net/http" "strconv" "github.com/gin-gonic/gin" ) type ErrorResponse struct { Message string `json:"message"` } type Handler struct { storage Storage } func NewHandler(storage Storage) *Handler { return &Handler{storage: storage} } func (h *Handler) CreateEmployee(c *gin.Context) { var employee Employee if err := c.BindJSON(&employee); err != nil { fmt.Printf("failed to bind json: %v", err.Error()) c.JSON(http.StatusBadRequest, ErrorResponse{ Message: err.Error(), }) return } h.storage.Insert(&employee) c.JSON(http.StatusOK, map[string]interface{}{ "id": employee.ID, }) } func (h *Handler) UpdateEmployee(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { fmt.Printf("failed to get id: %v", err.Error()) c.JSON(http.StatusBadRequest, ErrorResponse{ Message: err.Error(), }) return } var employee Employee if err := c.BindJSON(&employee); err != nil { fmt.Printf("failed to bind json: %v", err.Error()) c.JSON(http.StatusBadRequest, ErrorResponse{ Message: err.Error(), }) return } employee.ID = id if err := h.storage.Update(&employee); err != nil { fmt.Printf("failed to update employee: %v", err.Error()) c.JSON(http.StatusInternalServerError, ErrorResponse{ Message: err.Error(), }) return } c.JSON(http.StatusOK, employee) } func (h *Handler) GetEmployee(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { fmt.Printf("failed to get id: %v", err.Error()) c.JSON(http.StatusBadRequest, ErrorResponse{ Message: err.Error(), }) return } employee, err := h.storage.Get(id) if err != nil { fmt.Printf("failed to get employee: %v", err.Error()) c.JSON(http.StatusInternalServerError, ErrorResponse{ Message: err.Error(), }) return } c.JSON(http.StatusOK, employee) } func (h *Handler) DeleteEmployee(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { fmt.Printf("failed to get id: %v", err.Error()) c.JSON(http.StatusBadRequest, ErrorResponse{ Message: err.Error(), }) return } if err := h.storage.Delete(id); err != nil { fmt.Printf("failed to delete employee: %v", err.Error()) c.JSON(http.StatusInternalServerError, ErrorResponse{ Message: err.Error(), }) return } c.JSON(http.StatusOK, map[string]interface{}{ "status": "deleted", }) }