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

时间:2018-03-24 09:48:55

标签: mongodb go

我是GOlang的新手。所以,我将数据从html页面插入 mongodb 数据库。但是代码中存在错误。代码如下: -

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\n", 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>

从上面的代码中,当用户点击提交按钮时,用户将通过访问网址localhost:9090/login以html格式输入数据,然后数据将显示在终端中我评论mongodb代码但是当我想要保存时该数据然后它给我错误。

  

错误: - 2018/03/24 14:48:28 http:panic serving [:: 1]:44410:       运行       错误:索引超出范围       goroutine 5 [正在运行]:       净/ HTTP(*康恩).serve.func1(0xc420094c80)       /usr/local/go/src/net/http/server.go:1726 + 0xd0       恐慌(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       由net / http。(* Server).Serve创建       /usr/local/go/src/net/http/server.go:2795 + 0x27b

任何人都可以帮我解决我的问题。我只是想保存数据。在mongodb的文件中。

1 个答案:

答案 0 :(得分:1)

The docs明确说明(强调我的):

  

此字段[r.Form]仅在调用 ParseForm后才可用

您在调用ParseForm之前正在访问它。

此外,r.Form的类型为url.Values,因此请使用r.Form.Get()来读取字段的第一个值。