I am in the process of creating a POST HTTP request function in Go that will accept different data types through parameter but I am stuck when assigning value from switch statement to requestData variable.
Ideally, the requestData would be of nil type until we go to switch statement and then assign value and type to it. Any help appreciated :)
Error message on requestData: "syntax error: unexpected type, expecting type"
My code:
main() {
..
// CASE 1: we are passing the form of url.Values type
form := url.Values{}
form.Add("note", "john2424")
form.Add("http", "clear")
response := POST("www.google.co.uk", client, form) // first POST request
// CASE 2: we are passing the JSON data using []byte type
jsonData := []byte(`{"ids":[12345]}`)
response := POST("www.google.co.uk", client, jsonData) // second POST request
}
func POST(website string, client *http.Client, data interface{}) (bodyString string) {
var requestData type // <<<<<<< Change requestData to a variable from switch case
switch data.(type) { // switch case based on type
case url.Values: // URL form data
formattedData := data.(url.Values) // convert interface to url.Values
requestData := strings.NewReader(formattedData.Encode()) // *Reader type
case []byte: // JSON
formattedData := data.([]byte) // convert interface to []byte
requestData := bytes.NewBuffer(formattedData) // *Buffer type
default: // anything else
}
request, err := http.NewRequest("POST", website, requestData)
if err != nil {
log.Fatal(err)
}
response, err := client.Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
} else {
bodyString = string(body)
}
return
}