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 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低