我是 Go 新手并使用 gin 框架尝试创建用户对象:
const (
// CollectionArticle holds the name of the users collection
CollectionUser = "users"
)
// User table contains the information for each user
type User struct {
ID bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
Username string `json:"username" bson:"username"`
Email string `json:"email" bson:"email"`
Password string `json:"password" bson:"password"`
StatusID uint8 `json:"status_id" bson:"status_id"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
Deleted uint8 `json:"deleted" bson:"deleted"`
}
这是创建用户的控制器
// Create a user
func Create(c *gin.Context) {
db := c.MustGet("db").(*mgo.Database)
//to help debugging
x, _ := ioutil.ReadAll(c.Request.Body)
log.Printf("request body is: %s \n", string(x))
user := models.User{}
err := c.Bind(&user)
if err != nil {
c.Error(err)
return
}
//to help debugging
log.Printf("user is: %v", user )
log.Printf("username is: %s and emails is %s", user.Username, user.Email )
err = db.C(models.CollectionUser).Insert(user)
if err != nil {
c.Error(err)
}
c.Redirect(http.StatusMovedPermanently, "/users")
}
登记表是:
<form action="/user/create" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" placeholder="Enter the username of the user" >
</div>
<div class="form-group">
<label for="email">Email</label>
<input name="email" class="form-control" placeholder="Enter user email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
在终端我得到:
[GIN-debug] Listening and serving HTTP on :7000
[GIN] 2016/04/25 - 06:30:04 | 200 | 549.499µs | 127.0.0.1 | GET /register
request body is: username=bob&email=bob%40me.com&password=1234
user is: {ObjectIdHex("") 0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0}
username is: and emails is
如您所见username
,字段值email
被password
传递给控制器。当我检查users
mongo 数据库中的集合时,我看到对象已创建但从表单提交的字段为空。我无法弄清楚为什么会发生这种情况,所以感谢您的提示。