I'm new to Go and using gin framework trying to create a user object:
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"`
}
This is the controller to create user
// 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
", 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")
}
And the registration form is:
<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>
In the terminal I get:
[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
AS you can see username
, email
and password
field values are passed to the controller. When I check users
collection in the the mongo database, I see that the objects are created but the fields submitted from the form are empty.
I could not figure out why this happens, so appreciate your hints.