英文:
Function basics in Golang
问题
我刚开始学习Go语言,我觉得创建一个简单的Curl类型函数来处理不同类型的请求会很有趣。然而,我不确定最佳的方法是什么,而且在谷歌搜索中也没有找到太多有用的信息。
在类似Curl的请求中,可能有数据有效载荷,也可能没有,我不确定如何处理这种情况。在下面的示例中,理想情况下,我希望在函数声明中将data
默认设置为nil
,并使用if语句检查是否需要准备body
变量。
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)
}
在调用函数时,我可以将data设置为字符串false
并检查它,但这似乎太过hacky。最佳的方法是什么?
我希望调用函数的代码行尽可能简洁,函数本身要干净、简洁。所有尝试都变得有些庞大,包含了许多控制语句。
英文:
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.
答案1
得分: 1
一般来说,在Go语言中有一个叫做"零值"的概念,所以你最有可能想要做的是,如果data是一个空字符串,将body设置为nil
,或者相反的逻辑:
var body io.Reader // 接口的零值总是nil
if data != "" {
body = strings.NewReader(data)
}
req, err := http.NewRequest(method, "http://domain.com", body)
如果你需要有一个选项将请求的body设置为空字符串,那么只需使用*string
并检查它是否为nil。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论