gocron/routers/host/host.go

94 lines
2.5 KiB
Go
Raw Normal View History

2017-04-07 01:13:36 +00:00
package host
2017-04-07 09:26:46 +00:00
import (
"gopkg.in/macaron.v1"
"github.com/ouqiang/gocron/models"
"github.com/ouqiang/gocron/modules/utils"
"github.com/ouqiang/gocron/modules/logger"
2017-04-13 09:35:59 +00:00
"strconv"
2017-04-07 09:26:46 +00:00
)
2017-04-07 01:13:36 +00:00
func Index(ctx *macaron.Context) {
hostModel := new(models.Host)
hosts, err := hostModel.List()
if err != nil {
logger.Error(err)
}
ctx.Data["Title"] = "主机列表"
ctx.Data["Hosts"] = hosts
ctx.HTML(200, "host/index")
}
2017-04-07 01:13:36 +00:00
func Create(ctx *macaron.Context) {
ctx.Data["Title"] = "添加主机"
2017-04-16 08:24:09 +00:00
ctx.HTML(200, "host/host_form")
}
func Edit(ctx *macaron.Context) {
ctx.Data["Title"] = "编辑主机"
hostModel := new(models.Host)
id := ctx.ParamsInt(":id")
err := hostModel.Find(id)
if err != nil {
logger.Errorf("获取主机详情失败#主机id-%d", id)
}
ctx.Data["Host"] = hostModel
ctx.HTML(200, "host/host_form")
2017-04-07 01:13:36 +00:00
}
2017-04-07 09:26:46 +00:00
type HostForm struct {
2017-04-13 09:35:59 +00:00
Name string `binding:"Required;MaxSize(100)"`
Alias string `binding:"Required;MaxSize(32)"`
Username string `binding:"Required;MaxSize(32)"`
Password string `binding:"Required;MaxSize(64)"`
2017-04-07 09:26:46 +00:00
Port int `binding:"Required;Range(1-65535)"`
2017-04-13 09:35:59 +00:00
Remark string
2017-04-07 09:26:46 +00:00
}
func Store(ctx *macaron.Context, form HostForm) string {
2017-04-13 09:35:59 +00:00
json := utils.JsonResponse{}
2017-04-07 09:26:46 +00:00
hostModel := new(models.Host)
2017-04-13 09:35:59 +00:00
nameExist, err := hostModel.NameExists(form.Name)
if err != nil {
return json.CommonFailure("操作失败", err)
}
if nameExist {
return json.CommonFailure("主机名已存在")
}
2017-04-07 09:26:46 +00:00
hostModel.Name = form.Name
hostModel.Alias = form.Alias
hostModel.Username = form.Username
hostModel.Password = form.Password
hostModel.Port = form.Port
hostModel.Remark = form.Remark
2017-04-13 09:35:59 +00:00
_, err = hostModel.Create()
2017-04-07 09:26:46 +00:00
if err != nil {
2017-04-13 09:35:59 +00:00
return json.CommonFailure("保存失败", err)
2017-04-07 09:26:46 +00:00
}
2017-04-07 01:13:36 +00:00
2017-04-07 09:26:46 +00:00
return json.Success("保存成功", nil)
2017-04-13 09:35:59 +00:00
}
func Remove(ctx *macaron.Context) string {
id, err := strconv.Atoi(ctx.Params(":id"))
json := utils.JsonResponse{}
if err != nil {
return json.CommonFailure("参数错误", err)
}
taskModel := new(models.Task)
exist,err := taskModel.HostIdExist(int16(id))
if err != nil {
return json.CommonFailure("操作失败", err)
}
if exist {
return json.CommonFailure("有任务引用此主机,不能删除")
}
hostModel := new(models.Host)
_, err =hostModel.Delete(id)
if err != nil {
return json.CommonFailure("操作失败", err)
}
return json.Success("操作成功", nil)
2017-04-07 01:13:36 +00:00
}