dongyongyin5339 2018-10-28 14:55
浏览 123

根据switch语句更改变量类型

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
}
  • 写回答

1条回答 默认 最新

  • dsa4214 2018-10-28 16:00
    关注

    get the typed data into the switch

    typedData:=switch data.(type) {
    

    then use that to convert for instance

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

    Although @mkopriva 's playground example looks like a better idea

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!