无法使用gin中的mgo将表单数据插入数据库。

huangapple go评论112阅读模式
英文:

Cannot insert form data into database using mgo in gin

问题

我是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

如你所见,usernameemailpassword字段的值被传递给了控制器。当我在Mongo数据库中检查users集合时,我发现对象已经创建,但是从表单提交的字段为空。
我无法弄清楚为什么会发生这种情况,所以希望你能给我一些提示。

英文:

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 = &quot;users&quot;
)


// User table contains the information for each user
type User struct {
	ID  bson.ObjectId `json:&quot;_id,omitempty&quot; bson:&quot;_id,omitempty&quot;`
	Username string        `json:&quot;username&quot; bson:&quot;username&quot;`
	Email     string        `json:&quot;email&quot; bson:&quot;email&quot;`
	Password  string        `json:&quot;password&quot; bson:&quot;password&quot;`
	StatusID  uint8         `json:&quot;status_id&quot; bson:&quot;status_id&quot;`
	CreatedAt time.Time     `json:&quot;created_at&quot; bson:&quot;created_at&quot;`
	UpdatedAt time.Time     `json:&quot;updated_at&quot; bson:&quot;updated_at&quot;`
	Deleted   uint8         `json:&quot;deleted&quot; bson:&quot;deleted&quot;`
}

This is the controller to create user

// Create a user
func Create(c *gin.Context) {
	db := c.MustGet(&quot;db&quot;).(*mgo.Database)

	//to help debugging
	x, _ := ioutil.ReadAll(c.Request.Body)
    log.Printf(&quot;request body is: %s \n&quot;, string(x))	

	user := models.User{}
	err := c.Bind(&amp;user)
	if err != nil {
		c.Error(err)
		return
	}

	//to help debugging
    log.Printf(&quot;user is: %v&quot;, user )
    log.Printf(&quot;username is: %s and emails is %s&quot;, user.Username, user.Email )	
	
	err = db.C(models.CollectionUser).Insert(user)
	if err != nil {
		c.Error(err)
	}
	c.Redirect(http.StatusMovedPermanently, &quot;/users&quot;)
}

And the registration form is:

  &lt;form action=&quot;/user/create&quot; method=&quot;POST&quot;&gt;
  

    &lt;div class=&quot;form-group&quot;&gt;
      &lt;label for=&quot;username&quot;&gt;Username&lt;/label&gt;
      &lt;input type=&quot;text&quot; name=&quot;username&quot; class=&quot;form-control&quot; id=&quot;username&quot; placeholder=&quot;Enter the username of the user&quot; &gt;
    &lt;/div&gt;

    &lt;div class=&quot;form-group&quot;&gt;
      &lt;label for=&quot;email&quot;&gt;Email&lt;/label&gt;
      &lt;input name=&quot;email&quot; class=&quot;form-control&quot; placeholder=&quot;Enter user email&quot; /&gt;
    &lt;/div&gt;

    &lt;div class=&quot;form-group&quot;&gt;
    &lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt;
        &lt;input type=&quot;password&quot; name=&quot;password&quot; class=&quot;form-control&quot; placeholder=&quot;Password&quot; required&gt;
    &lt;/div&gt;

    &lt;button type=&quot;submit&quot; class=&quot;btn btn-default&quot;&gt;Submit&lt;/button&gt;

  &lt;/form&gt;

In the terminal I get:

[GIN-debug] Listening and serving HTTP on :7000
[GIN] 2016/04/25 - 06:30:04 | 200 |     549.499&#181;s | 127.0.0.1 |   GET     /register
request body is: username=bob&amp;email=bob%40me.com&amp;password=1234 
user is: {ObjectIdHex(&quot;&quot;)    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.

答案1

得分: 2

根据gin文档,你需要使用form标签来定义字段的结构,例如:

User     string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
英文:

according to the gin document, you need form tag to struct fields. like:

User     string `form:&quot;user&quot; binding:&quot;required&quot;`
Password string `form:&quot;password&quot; binding:&quot;required&quot;`

huangapple
  • 本文由 发表于 2016年4月25日 12:34:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/36832072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定