0

I have function that get ID from POST request and deleting element with number equal to ID with similar code:

w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding")

switch r.Method {
case "POST":
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Print(err)
        return
    }

    type row struct {
        Row int
    }
    var rowId row
    json.Unmarshal(body, &rowId)

    var id = rowId.Row
    type requestBody struct {
        Name        string
        Id          int
        Price       int
        Img         string
        Link        string
        Description string
    }
    var request requestBody
    json.Unmarshal([]byte(body), &request)

    file, _ := ioutil.ReadFile("./static/nuts.json")

    data := []requestBody{}

    json.Unmarshal(file, &data)
    data = append(data[:id])

    dataBytes, err := json.MarshalIndent(data, "", "   ")
    if err != nil {
        fmt.Print(err)
    }

    err = ioutil.WriteFile("./static/nuts.json", dataBytes, 0644)
    if err != nil {
        fmt.Print(err)
    }
}

But if I have 3 elements in JSON, and delete 2nd element, next element will delete to. I'm new to GO, and I don't know how to fix this problem. Help me pls

3
  • 1
    github.com/golang/go/wiki/SliceTricks Commented Mar 31, 2020 at 10:10
  • @mkopriva thank you, It's working now. Can I post your answer as answer or you will do it by yourself? Commented Mar 31, 2020 at 10:37
  • go ahead you can post the answer. Commented Mar 31, 2020 at 10:46

1 Answer 1

1

Answer was change this:

data = append(data[:id])

to this:

data = append(data[:id], data[id+1:]...)

And everything will work

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

Comments

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.