Reputation: 2402
I am just starting out learning Go and I thought it would be fun to create a simple Curl type function to handle different types of requests. However, I'm not sure on what the best approach should be and I'm not having much luck with Google searches.
With a curl like request, there may and may not be a data payload and I'm unsure how best to handle this situation. Ideally in the function declaration (in the example below) I would like to have data
default to nil
and an if clause check whether to prepare the body
variable.
connect("POST", `{"name":"bob","age":123}`)
func connect(method string, data string) {
body := strings.NewReader(data)
req, err := http.NewRequest(method, "http://domain.com", body)
}
When calling the function, I could set data to string false
and check for that, but that seems way too hacky. What would the best approach be?
I would like to keep the line of code calling the function as brief as possible and the function itself to be clean and minimilistic. All attempts have become a little too big with many control statements.
Upvotes: 0
Views: 91
Reputation: 3117
Generally speaking in Go there's the concept of "Zero values", so what you'll most likely want to do is to set body to nil
if data is an empty string, or the opposite logic:
var body io.Reader // Zero value of interfaces is always nil
if data != "" {
body = strings.NewReader(data)
}
req, err := http.NewRequest(method, "http://domain.com", body)
If you need to have an option to set the request's body to be an empty string, then just use *string
and check if it's nil.
Upvotes: 1