[英]How to write a map inside a array and adding that to a json file in go?
I want to make a sign-up server using go where the users are stored in a JSON file called users.json
with this format:我想使用 go 制作注册服务器,其中用户存储在名为users.json
的 JSON 文件中,格式如下:
[
{
"email": "email",
"password": "password"
},
{
"email": "email",
"password": "password"
},
...
]
Right now I'm using this code:现在我正在使用这段代码:
func signup(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
type User struct {
Email string
Password string
}
user := User{}
user.Email = r.Form["email"][0]
user.Password = r.Form["password"][0]
content, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
}
err = ioutil.WriteFile("users.json", content, 0644)
if err != nil {
log.Fatal(err)
}
}
The issue with it is that if a new user signed up it deletes the old data in the JSON file and it stores the informations in this format:它的问题是,如果新用户注册它会删除 JSON 文件中的旧数据,并以这种格式存储信息:
{
"Email": "email",
"Password": "password"
}
I'm new to go and have no idea on how to do it.我是 go 的新手,不知道该怎么做。
Doc says: WriteFile writes data to the named file, creating it if necessary. Doc 说:WriteFile 将数据写入指定文件,并在必要时创建它。 If the file does not exist, WriteFile creates it with permissions perm (before umask);如果文件不存在,WriteFile 使用权限 perm(在 umask 之前)创建它; otherwise WriteFile truncates it before writing, without changing permissions.否则 WriteFile 在写入之前将其截断,而不更改权限。
https://pkg.go.dev/os#WriteFile https://pkg.go.dev/os#WriteFile
You must append to the JSON file.您必须 append 到 JSON 文件。 Follow this thread to see how you can perform JSON file append.按照此线程查看如何执行 JSON 文件 append。 https://stackoverflow.com/a/44642209/9787555 https://stackoverflow.com/a/44642209/9787555
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.