我有2种方法,分别用于GET
和POST
。
第一个是:
var Join map[string]int
func MapTheFields(c *gin.Context) {
var data []string
//Open the csv file
csvFile, _ := os.Open("customers.csv")
reader := csv.NewReader(csvFile)
line, _ := reader.ReadAll()
for i := 0; i < len(line[0]); i++ {
Join = map[string]int{
line[0][i]: i,
}
data = append(data, line[0][i])
}
GetSuccessResponse(c, "The Mappings are:", data)
}
第二个也与第一个相似。它只是将值保存到数据库中。
我一直面临的问题是,我必须将从csv文件获得的字段映射到项目中的字段,为此,我制作了名为Join
的映射,如上所示,我在第二个函数中以
line[i][Join["Last Name"]]
但是我得到Join["Last Name"]
的值为0
,尽管它的值为1
,无论我在哪里使用联接作为索引,该值都是零,我总是结束仅包含前四个值,然后是超出范围的索引错误。
其余代码为:
func ImportCustomerData(c *gin.Context) {
//Open the csv file
csvFile, _ := os.Open("customers.csv")
reader := csv.NewReader(csvFile)
var (
user models.User
customer models.Customer
address models.UserAddress
addresses []models.UserAddress
people []models.Customer
users []models.User
)
line, _ := reader.ReadAll()
for i := 1; i < len(line[0]); i++ {
//Initialize address details
address.Address = line[i][Join["address"]]
address.City = line[i][Join["City"]]
address.State = line[i][Join["State"]]
address.Zipcode = line[i][Join["Postal Code"]]
savedAddress := SaveNewAddress(address, merchantDb)
//Initalize user details
user.FirstName = line[i][Join["First Name"]]
user.LastName = line[i][Join["Last Name"]]
user.CompanyName = line[i][Join["Company Name"]]
user.EmailId = line[i][Join["Email"]]
user.PhoneNumber = line[i][Join["Phone"]]
}
}
邮递员中第一个功能的输出是:
{
"response": {
"code": 200,
"api_status": 1,
"message": "The Mappings are:",
"data": [
"First Name",
"Last Name",
"Company Name",
"Email",
"Address",
"City",
"State",
"Postal Code",
"Phone",
"Date Created",
"Stripe ID",
"Date of First Booking",
"Date of Last Booking",
"Frequency of Last Booking",
"Date of Next Booking",
"Notes",
"Customer ID"
]
}
}
我在哪里弄错了?
答案 0 :(得分:1)
您每次都在MapTheFields()
中分配一个新地图:
for i := 0; i < len(line[0]); i++ {
Join = map[string]int{
line[0][i]: i,
}
data = append(data, line[0][i])
}
Join
类型的映射,应该首先分配,声明Join像这样:
Join = make(map[string]int) //declaration can be global
用以下代码替换MapTheFields()
中的代码段:
for i := 0; i < len(line[0]); i++ {
Join[line[0][i]] = i
data = append(data, line[0][i])
}