donglin1692
donglin1692
2018-03-24 09:48

如何使用golang在mongodb中插入用户信息?

已采纳

I am new on GOlang. So, I am inserting the data from an html page to mongodb database. But there is an error in the code. The code is below:-

package main

import (
  "fmt"
  "gopkg.in/mgo.v2"
  "gopkg.in/mgo.v2/bson"
  "html/template"
  "log"
  "net/http"
  "strings"
)
type USER struct {
    Username string      `bson:"Username" json:"Username,omitempty"`
    Password string      `bson:"Password" json:"Password,omitempty"`
}
func sayhelloName(w http.ResponseWriter, r *http.Request) {
   r.ParseForm()
   fmt.Println(r.Form)
   fmt.Println(r.Form["url_long"])
   for k, v := range r.Form {
      fmt.Println("key:", k)
      fmt.Println("val:", strings.Join(v, ""))
    }
    fmt.Fprintf(w, "Hello astaxie!")
}
func login(w http.ResponseWriter, r *http.Request) {
   fmt.Println("method:", r.Method)
   if r.Method == "GET" {
       t, _ := template.ParseFiles("index.html")
       t.Execute(w, nil)
   } else {
         //connection with mongodb
        session, err := mgo.Dial("mongodb://127.0.0.1:27017/so")
        if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    c := session.DB("so").C("insrt")
    doc := USER{
        Username: r.Form["username"][0],
        Password: r.Form["password"][0],
    }
    err = c.Insert(doc)
    if err != nil {
        panic(err)
    }
    r.ParseForm()
    fmt.Printf("%T
", r.Form["username"])
    fmt.Println("---------------------------------------------")
    fmt.Println("username:", r.Form["username"][0])//output:- username: user_name
    fmt.Println("password:", r.Form["password"][0])//password:- password: user_password
   }
}
func main() {
   http.HandleFunc("/", sayhelloName)
   http.HandleFunc("/login", login)
   err := http.ListenAndServe(":9090", nil)
   if err != nil {
      log.Fatal("ListenAndServe: ", err)
   }
}

index.html

 <html>
 <head>
 <title></title>
 </head>
 <body>
    <form action="/login" method="post">
        Username:<input type="text" name="username">
        Password:<input type="password" name="password">
        <input type="submit" value="Login">
    </form>
  </body>
</html>

From the above code the user will entered the data in the html form by accessing url localhost:9090/login when user click on submit button then the data will shown in the terminal I comment the mongodb code but when i want to save that data then it gives me error.

error:-2018/03/24 14:48:28 http: panic serving [::1]:44410: runtime error: index out of range goroutine 5 [running]: net/http.(*conn).serve.func1(0xc420094c80) /usr/local/go/src/net/http/server.go:1726 +0xd0 panic(0x78aa20, 0xa03de0) /usr/local/go/src/runtime/panic.go:505 +0x229 main.login(0x846c80, 0xc42015c0e0, 0xc42018a000) /home/iron/go/src/go-training/pagesweb/main.go:48 +0x767 net/http.HandlerFunc.ServeHTTP(0x8147d0, 0x846c80, 0xc42015c0e0, 0xc42018a000) /usr/local/go/src/net/http/server.go:1947 +0x44 net/http.(*ServeMux).ServeHTTP(0xa132c0, 0x846c80, 0xc42015c0e0, 0xc42018a000) /usr/local/go/src/net/http/server.go:2337 +0x130 net/http.serverHandler.ServeHTTP(0xc42008b2b0, 0x846c80, 0xc42015c0e0, 0xc42018a000) /usr/local/go/src/net/http/server.go:2694 +0xbc net/http.(*conn).serve(0xc420094c80, 0x847080, 0xc420146040) /usr/local/go/src/net/http/server.go:1830 +0x651 created by net/http.(*Server).Serve /usr/local/go/src/net/http/server.go:2795 +0x27b

Anybody can help me to solve my problem. I just want to save the data. in document of mongodb.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doutou6803 doutou6803 3年前

    The docs clearly state (emphasis mine):

    This field [r.Form] is only available after ParseForm is called.

    You are accessing it before calling ParseForm.

    Also, r.Form is of type url.Values, so use r.Form.Get() to read the first value of a field.

    点赞 评论 复制链接分享

相关推荐