Я новичок в 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, я вижу, что объекты созданы, но поля, отправленные из формы, пусты. Я не мог понять, почему это происходит, поэтому ценю ваши подсказки.