我正在使用gin库创建一个简单的 crud webapp。我有一个路由设置,它检查一个参数,id
如果它应该被渲染,否则返回带有 id 的员工(如果存在)当我渲染获取错误消息的模板时渗入其中。这是一个快照add
admin-employee-add.html
admin-employee-add.html
404 not found
管理员-员工-add.html
{{template "pageStart.html" .}}
<form class="form-horizontal admin-employee">
<div class="row form-group">
<label for="employeeNumber" class="col-lg-2 control-label text-right">Employee #</label>
<div class="col-lg-4">
<span>new</span>
</div>
<label for="status" class="col-lg-2 control-label text-right">Status</label>
<div class="col-lg-4">
<span>new</span>
</div>
</div>
<div class="row form-group">
<label for="firstName" class="col-lg-2 control-label text-right">Name</label>
<div class="col-lg-2">
<input type="text" id="firstName" name="firstName" class="form-control">
</div>
<div class="col-lg-2">
<input type="text" id="lastName" name="lastName" class="form-control">
</div>
</div>
<div class="row form-group">
<label for="startDate" class="col-lg-2 control-label text-right">Start Date</label>
<div class="col-lg-2">
<input type="date" id="startDate" name="startDate" class="form-control">
</div>
<label for="pto" class="control-label col-lg-2 col-lg-offset-2 text-right">PTO</label>
<div class="col-lg-3">
<input type="number" id="pto" name="pto" class="form-control">
</div>
<div class="col-lg-1">
days
</div>
</div>
<div class="row form-group">
<label for="position" class="col-lg-2 control-label text-right">Position</label>
<div class="col-lg-2">
<select name="position" id="position" class="form-control">
<option value="CEO">CEO</option>
<option value="CTO">CTO</option>
<option value="COO">COO</option>
<option value="WorkerBee">Worker Bee</option>
</select>
</div>
</div>
<div class="col-lg-3 col-lg-offset-8">
<button type="submit" class="btn btn-lg admin-primary">Create</button>
</div>
</form>
创建错误的路线
r.GET("/employee/:id/", func(c *gin.Context) {
id := c.Param("id")
if id == "add" {
c.HTML(http.StatusOK, "admin-employee-add.html", nil)
}
employee, ok := employees[id]
if !ok {
c.String(http.StatusNotFound, "404 not found", nil)
} else {
c.HTML(http.StatusOK, "admin-employee-edit.html", map[string]interface{}{
"Employee": employee,
})
}
})
错误似乎是因为 gin 正在尝试重定向/add
->/add/
但我已经/add/
在浏览器中使用该路由。
gin的调试日志
[GIN-debug] GET /login --> main.registerRoutes.func2 (3 handlers)
[GIN-debug] GET /employee/:id/ --> main.registerRoutes.func3 (3 handlers)
[GIN-debug] GET /employee/:id/vacation --> main.registerRoutes.func4 (3 handlers)
[GIN-debug] GET /admin/ --> main.registerRoutes.func5 (4 handlers)
[GIN-debug] Listening and serving HTTP on :3000
[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with
404
[GIN] 2016/05/01 - 14:12:13 | 404 | 1.101426ms | 127.0.0.1 | GET /employee/add/
我尝试将路线更改为/:id
然后显示错误。
redirecting request 301: /employee/add/ --> /employee/add
[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with
404
注意:此错误可以通过在 .return
末尾添加一个轻松解决if id == "add"
。但是这种模式使代码看起来不那么枯燥。这似乎是一个更大的httprouter
问题。