-3

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:

[
    {
        "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:

{
    "Email": "email",
    "Password": "password"
}

I'm new to go and have no idea on how to do it.

4
  • 2
    (1) Do not store passwords in plain text. (2) To prevent an attacker from causing server panic, replace r.Form[key][0] with r.Form.Get(key). Commented Aug 30, 2022 at 19:42
  • 1
    if you have a fatal error, make sure you're interrupting program execution . if json.Marshal fails in your code, you stil write out the content to the file Commented Aug 30, 2022 at 19:43
  • 2
    this implementation doesn't make sense without some sort of lock on the file (otherwise concurrent requests will writ to the file at the same time, almost certainly munging up the content). If you want to preserve existing file content, you need to read the file, parse it, append a new User to the resultant list, and then marshal and write the file out again. Json files do not a database make. Commented Aug 30, 2022 at 19:45
  • 1
    you might also want to ask yourself, what happens if somebody submits the same email address twice? Gets 2 entries in the file? Commented Aug 30, 2022 at 19:45

1 Answer 1

0

Doc says : WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.

https://pkg.go.dev/os#WriteFile

You must append to the JSON file. Follow this thread to see how you can perform JSON file append. https://stackoverflow.com/a/44642209/9787555

Sign up to request clarification or add additional context in comments.

1 Comment

Appending will still yield invalid JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.