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

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题