【问题标题】:Change variable type based on switch statement根据 switch 语句更改变量类型
【发布时间】:2019-04-01 15:16:30
【问题描述】:

我正在 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
}

【问题讨论】:

  • 使用 io.Reader 并且不要在 case 中做简短的变量声明。请阅读有关接口的更多信息并参加围棋之旅(再一次)。
  • 可以设置为空界面
  • 不需要错误的行。请参阅此 Tour of Go 示例了解如何操作 tour.golang.org/methods/16
  • 嗨 Vorsprung。我的 http.NewRequest 需要 requestData 变量,如果我删除了这个变量,就没有办法了。除了将整个请求复制到每个 switch case 之外。嗨 poy,我以前做过,但它不适用于 http.Request "request, err := http.NewRequest("POST", website, requestData.())"

标签: variables go interface switch-statement


【解决方案1】:

将输入的数据输入开关

typedData:=switch data.(type) {

然后用它来转换例如

case []byte: // JSON
        requestData := bytes.NewBuffer(typedData) // *Buffer type

虽然 @mkopriva 的游乐场示例看起来更好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2023-03-11
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多