donglin1692 2018-03-24 09:48
浏览 81
已采纳

如何使用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 2018-03-24 10:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分