variables - 根据 switch 语句更改变量类型
问题描述
我正在 Go 中创建一个 POST HTTP 请求函数,该函数将通过参数接受不同的数据类型,但是在将 switch 语句中的值分配给 requestData 变量时我被卡住了。
理想情况下,requestData 将是 nil 类型,直到我们转到 switch 语句然后为其分配值和类型。任何帮助表示赞赏:)
requestData 上的错误消息:“语法错误:意外类型,预期类型”
我的代码:
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
}
解决方案
将输入的数据输入开关
typedData:=switch data.(type) {
然后用它来转换例如
case []byte: // JSON
requestData := bytes.NewBuffer(typedData) // *Buffer type
尽管@mkopriva 的游乐场示例看起来是一个更好的主意
推荐阅读
- android - 如何从 WebView 的 HTML 页面访问外部存储?
- libgdx - libgdx MeshBuilder - 为什么不推荐使用这么多方法?
- c# - 闪屏后出现白屏
- reactjs - 'ApolloProvider' 不是从 React 中的'apollo-client' 导出的
- python - 如何突出显示特定工作日(周六和周日)的带有垂直颜色条的绘图线图?
- java - Spring Cloud Kubernetes 应用程序在 Pod 中运行时未检测到
- tensorflow - 训练 yolov3 时出错:- ValueError: tf.function-decorated 函数试图在非第一次调用时创建变量
- c++ - 为什么要写 `!!x`,当 `x` 可以呢?
- apache-kafka - 如何从一种输入类型写入多种输出类型?
- javascript - 为什么我不能创建用户?