dsa45132 2015-11-02 02:38
浏览 232
已采纳

将参数传递给GET请求

I cannot seem to figure how to do this in go.

I was following this tutorial:

https://github.com/parnurzeal/gorequest

and I can pass parameters using Header, which I think is a bad idea.

I am basically looking for go version of python

In [28]: import requests

In [29]: r = requests.get("http://localhost:8000/get_result", params={"number": 40})

Following is my code for my REST API:

package main

import (
    "net/http"
    "strconv"
    "fmt"
)

func make_result(w http.ResponseWriter, r *http.Request) {

    fmt.Println(r)

    err := r.ParseForm()
    if err != nil {
        panic(err)
    }

    number_string := r.Form["number"][0]
    // number_string := r.Header["Number"][0] header solution
    number, err := strconv.Atoi(number_string)
    if err != nil {
        panic(err)
    }

    fmt.Fprint(w, fmt.Sprint(number * 5))

}

func main() {
    http.HandleFunc("/get_result", make_result)
    http.ListenAndServe("localhost:8000", nil)
}

I am trying to call it using this code:

package main

import(
    "fmt"    
    "reflect"
    "github.com/parnurzeal/gorequest"

)

func main() {

    resp, body, errs := gorequest.New().
        Get("http://localhost:8000/get_result").
        Set("Number", "7").      // Changes the Header 
        Type("form").            // These two lines appear 
        Send(`{"number": 5}`).   // to be irrelevant 
        End()


    fmt.Println(errs)
    fmt.Println(resp)
    fmt.Println(body)

}

The above is similar to python's:

In [34]: r = requests.get("http://localhost:8000/get_result", headers={"Number": 7})

When I am using the python method (using params) to call the api, I see /get_result?number=7 <nil> <nil> line being printed as a part of request object. But am don't see it in my go version, so I must be calling it wrong. What am I missing?

  • 写回答

1条回答 默认 最新

  • duanjian4698 2015-11-02 03:24
    关注

    Looks like you need to use Param to do this.

    Also the standard library's NewRequest returns a Request struct with a member URL that has a function Query that you can use to Add parameters to your query before issuing the request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)