You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Golang+Gin+Gorm+PostgreSQL的HTML新增员工功能实现求助

实现HTML表单创建员工并存入数据库的解决方案

1. 调整结构体,添加表单绑定标签

HTML表单提交的数据需要和Gin的绑定机制匹配,给结构体每个字段加上form标签,与表单输入框的name属性对应;同时给主键字段添加自增配置,避免手动输入ID导致重复:

type Funcionarios struct {
    IDFuncionario       int    `json:"id_funcionario" gorm:"primaryKey;autoIncrement" form:"id_funcionario"`
    NomeFuncionario     string `json:"nome_funcionario" form:"nome_funcionario"`
    IdadeFuncionario    int    `json:"idade_funcionario" form:"idade_funcionario"`
    EnderecoFuncionario string `json:"endereco_funcionario" form:"endereco_funcionario"`
    FuncaoFuncionario   string `json:"funcao_funcionario" form:"funcao_funcionario"`
    SalarioFuncionario  int    `json:"salario_funcionario" form:"salario_funcionario"`
    DataContratacao     string `json:"data_contratacao_funcionario" form:"data_contratacao"`
}

2. 修改创建接口,支持表单绑定并优化跳转逻辑

原接口仅支持JSON数据绑定,现在改成绑定表单数据,同时添加错误处理,创建成功后重定向到员工列表页面,让用户直接看到新增数据:

func (h handler) createFuncionario(c *gin.Context) {
    var addFunc Funcionarios
    // 绑定表单数据,检查绑定错误
    if err := c.ShouldBind(&addFunc); err != nil {
        c.HTML(http.StatusBadRequest, "index.html", gin.H{
            "error":    "填写信息有误,请检查后重试",
            "listFunc": getFuncionarios(h),
        })
        return
    }

    // 存入数据库,检查存储错误
    if err := h.db.Create(&addFunc).Error; err != nil {
        c.HTML(http.StatusInternalServerError, "index.html", gin.H{
            "error":    "创建员工失败,请稍后重试",
            "listFunc": getFuncionarios(h),
        })
        return
    }

    // 重定向到员工列表页面
    c.Redirect(http.StatusFound, "/users/listHTML")
}

// 封装获取员工列表的函数,避免重复代码
func getFuncionarios(h handler) []Funcionarios {
    var list []Funcionarios
    h.db.Find(&list)
    return list
}

3. 修改index.html,添加员工创建表单

在HTML页面中添加表单区域,放在员工列表上方,表单提交路径对应创建接口,输入框name属性与结构体form标签一致:

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Funcionários</title>
    <style>
        .form-container {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 8px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: inline-block;
            width: 150px;
            font-weight: bold;
        }
        input {
            padding: 5px;
            width: 250px;
        }
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .error {
            color: red;
            margin-bottom: 15px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <h2>Criar Novo Funcionário</h2>
        {{ if .error }}
            <div class="error">{{ .error }}</div>
        {{ end }}
        <form method="POST" action="/users/create">
            <div class="form-group">
                <label>Nome:</label>
                <input type="text" name="nome_funcionario" required>
            </div>
            <div class="form-group">
                <label>Idade:</label>
                <input type="number" name="idade_funcionario" min="18" required>
            </div>
            <div class="form-group">
                <label>Endereço:</label>
                <input type="text" name="endereco_funcionario" required>
            </div>
            <div class="form-group">
                <label>Função:</label>
                <input type="text" name="funcao_funcionario" required>
            </div>
            <div class="form-group">
                <label>Salário:</label>
                <input type="number" name="salario_funcionario" min="0" step="0.01" required>
            </div>
            <div class="form-group">
                <label>Data de Contratação:</label>
                <input type="date" name="data_contratacao" required>
            </div>
            <button type="submit">Criar Funcionário</button>
        </form>
    </div>

    <h2>Lista de Funcionários</h2>
    <table>
        <tr>
            <th>ID</th>
            <th>Nome</th>
            <th>Idade</th>
            <th>Endereço</th>
            <th>Função</th>
            <th>Salário</th>
            <th>Data de Contratação</th>
        </tr>
        {{ range .listFunc }}
        <tr>
            <td>{{ .IDFuncionario }}</td>
            <td>{{ .NomeFuncionario }}</td>
            <td>{{ .IdadeFuncionario }}</td>
            <td>{{ .EnderecoFuncionario }}</td>
            <td>{{ .FuncaoFuncionario }}</td>
            <td>{{ .SalarioFuncionario }}</td>
            <td>{{ .DataContratacao }}</td>
        </tr>
        {{ end }}
    </table>
</body>
</html>

4. 测试验证

  1. 启动Gin服务
  2. 访问http://localhost:8086/users/listHTML,页面会显示创建表单和员工列表
  3. 填写表单信息并提交,页面会重定向回列表,可看到新增员工
  4. 查看PostgreSQL数据库,确认新员工数据已存入

注意事项

  • 确保PostgreSQL表中id_funcionario字段为自增主键,Gorm的autoIncrement标签会自动生成该配置
  • 若需规范处理日期,可将DataContratacao字段类型改为time.Time,并添加标签gorm:"type:date" form:"data_contratacao"
  • 可根据需求添加更多表单验证规则,如输入长度限制、格式检查等

内容的提问来源于stack exchange,提问作者Guilherme Rodrigues

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:20:28