Nie mogę wydawać się, jak to zrobić w go
.Przekazywanie parametrów do żądania GET
byłem po ten poradnik:
https://github.com/parnurzeal/gorequest
i mogę przekazać parametry używając Header
, co moim zdaniem jest to zły pomysł.
Ja w zasadzie szuka go
wersji python
In [28]: import requests
In [29]: r = requests.get("http://localhost:8000/get_result", params={"number": 40})
Poniżej mój kod dla mojego 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)
}
Próbuję wywołać go za pomocą tego kodu:
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)
}
Powyższe jest podobne do pythona:
In [34]: r = requests.get("http://localhost:8000/get_result", headers={"Number": 7})
Kiedy używam metody Pythona (używając params) do wywołania API, widzę /get_result?number=7 <nil> <nil>
linia jest drukowana jako część request object
. Ale nie widzę tego w mojej wersji go, więc muszę to nazwać błędem. czego mi brakuje?