blt/web/routes/hardware.go

66 lines
1.5 KiB
Go
Raw Normal View History

2023-12-02 22:37:46 -05:00
package routes
import (
"fmt"
"log"
"net/http"
"github.com/flamego/binding"
"github.com/flamego/flamego"
"github.com/flamego/template"
"github.com/flamego/validator"
"git.metaunix.net/bitgoblin/blt/models"
"git.metaunix.net/bitgoblin/blt/web/forms"
)
func HardwareGetList(t template.Template, data template.Data) {
// add hardwares to template
var hardware []models.Hardware
2024-05-29 09:16:32 -04:00
models.DB.Find(&hardware)
data["hardware"] = hardware
2023-12-02 22:37:46 -05:00
data["title"] = "List of Hardware"
t.HTML(http.StatusOK, "hardware/list")
2023-12-02 22:37:46 -05:00
}
2024-05-29 08:37:51 -04:00
func HardwareGetView(c flamego.Context, t template.Template, data template.Data) {
// find hardware ID from request
2024-05-29 08:39:27 -04:00
hardwareID := c.Param("hardware_id")
2024-05-29 08:37:51 -04:00
// find hardware from DB
var hardware models.Hardware
2024-05-29 09:16:32 -04:00
models.DB.First(&hardware, hardwareID)
2024-05-29 08:37:51 -04:00
data["hardware"] = hardware
2024-05-29 08:39:27 -04:00
data["title"] = hardware.Name
t.HTML(http.StatusOK, "hardware/view")
2024-05-29 08:37:51 -04:00
}
2023-12-02 22:37:46 -05:00
func HardwareGetCreate(t template.Template, data template.Data) {
data["title"] = "Add New Hardware"
t.HTML(http.StatusOK, "hardware/create")
}
func HardwarePostCreate(c flamego.Context, form forms.HardwareForm, errs binding.Errors) {
if len(errs) > 0 {
var err error
switch errs[0].Category {
case binding.ErrorCategoryValidation:
err = errs[0].Err.(validator.ValidationErrors)[0]
default:
err = errs[0].Err
}
log.Fatal(err)
}
hardware := models.Hardware{
Name: form.Name,
Type: form.Type,
}
_ = models.DB.Create(&hardware)
c.Redirect(fmt.Sprintf("/hardware/%d", hardware.ID))
}