Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consume a DELETE endpoint from golang

Tags:

go

I am working in a Go project, and I need to perform some operations over an external API: GET, PUT, POST and DELETE. Currently I am using net/http, and I created a &http.Client{} to make GET and PUT. That is working as expected.

Now I need to perform a DELETE and I cannot find anything about it. Is it supported? Basically, I need to call a URL like this:

somedomain.com/theresource/:id
Method: DELETE

How can I perform that?

like image 934
Sredny M Casanova Avatar asked Sep 19 '17 21:09

Sredny M Casanova


1 Answers

Here is a small example of how to do it:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func sendRequest() {
    // Request (DELETE http://www.example.com/bucket/sample)

    // Create client
    client := &http.Client{}

    // Create request
    req, err := http.NewRequest("DELETE", "http://www.example.com/bucket/sample", nil)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Fetch Request
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()

    // Read Response Body
    respBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Display Results
    fmt.Println("response Status : ", resp.Status)
    fmt.Println("response Headers : ", resp.Header)
    fmt.Println("response Body : ", string(respBody))
}
like image 110
nbari Avatar answered Oct 28 '22 22:10

nbari