0

我的 csv 文件具有这样的用户数据:

 firstname|lastname|Email| other fields are empty
          |        |     |
          |        |     |
          |        |     |
          |        |     |

我正在使用的代码是:

 package main

import (
 "encoding/csv"
 "gopkg.in/mgo.v2"
 "io"
 "log"
 "os"
)

type Mongo struct {
  // Id          int    `json:"_id" bson:"_id"`
  FirstName   string `json:"first_name,omitempty" bson:"first_name,omitempty"`
  LastName    string `json:"last_name,omitempty" bson:"last_name,omitempty"`
  Email       string `json:"email,omitempty" bson:"email,omitempty"`
  PhoneNumber string `json:"phone_number,omitempty" bson:"phone_number,omitempty"`
  Gender      string `json:"gender,omitempty" bson:"gender,omitempty"`
  Address     string `json:"address,omitempty" bson:"address,omitempty"`
  Apartment   string `json:"apartment,omitempty" bson:"apartment,omitempty"`
  Description string `json:"description,omitempty" bson:"description,omitempty"`
 }

func main() {

 session, err := mgo.Dial("localhost")
 if err != nil {
    panic(err)
 }

 defer session.Close()
 session.SetMode(mgo.Monotonic, true)

 c := session.DB("Import_Users").C("users")

 file, err := os.Open("customers.csv")

 if err != nil {
    panic(err)
 }
 defer file.Close()

 reader := csv.NewReader(file)

 for {
    record, err := reader.Read()
    if err == io.EOF {
        break
    } else if err != nil {
        panic(err)
    }

    err = c.Insert(&Mongo{record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7]})

    if err != nil {
        panic(err)
    }
    log.Printf("%#v", record)
 }
}

运行时出现错误:

错误:- 恐慌:运行时错误:索引超出范围

goroutine 1 [运行]: main.main() /home/iron/go/src/go-training/How_to_load_csv_file/main.go:53 +0x830 退出状态 2

我该如何解决这个错误?

4

1 回答 1

0

确保您有切片元素record[0]through record[7]。添加空的填充元素。例如,

reader := csv.NewReader(file)
padding := make([]string, 8)  // 0 thru 7
for {
    record, err := reader.Read()
    if err == io.EOF {
        break
    } else if err != nil {
        panic(err)
    }
    record = append(record, padding...)
    err = c.Insert(&Mongo{record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7]})

    if err != nil {
        panic(err)
    }
    log.Printf("%#v", record)
}
于 2018-06-27T11:51:17.133 回答