mokoko
(Casper)
1
ı need this python code convert to golang pls
import requests
def api():
response = requests.get("https://reqres.in/api/users?page=1").json()
print("Page : ",response["page"])
print("Per_page : ",response["per_page"])
print("total: ",response["total"])
print("total_pages",response["total_pages"])
data = (response["data"])
for i in data:
print("id : "," ",i["id"]," ","Email : ",i["email"]," ","First Name : ",i["first_name"],"Last Name : "," ",i["last_name"]," ","Avatar: ",i["avatar"],"\n")
avatars = i["avatar"]
avatar_name = (avatars[28:])
contentR = requests.get(avatars)
with open(i["first_name"]+" "+i["last_name"]+" "+avatar_name,"wb") as f:
f.write(contentR.content)
api()
hi,
the question is if you understand what this Python code does.
In short it:
- make a GET request to a service
- prints some info
- iterates over the results
- downloads the avatars and save theme to the disk.
what do you tried so far ?
bijwaard
(Dennis Bijwaard)
3
Hi Casper,
Your code looks like a REST endpoint, you probably need one or more of the following packages to do this in golang:
- “net/http” for REST requests/responses
- “html/template” for templates similar to Flask / jinja
- “github.com/gorilla/mux” for REST router
- “encoding/json” for parsing a JSON request and generating JSON response
- “io/ioutil” for easier read/write
Since it is unclear what the type of the message parts is, you could try to parse the response with e.g.:
req, err := http.NewRequest("GET", "https://reqres.in/api/users?page=1", nil)
if err != nil {
fmt.Println("Error is req: ", err)
}
// create a Client
client := &http.Client{}
// Do sends an HTTP request and
resp, err := client.Do(req)
if err != nil {
fmt.Println("error in send req: ", err)
}
respBody, _ := ioutil.ReadAll(resp.Body)
var respMap map[string]interface{}
json.Unmarshal(respBody,&respMap)
log.Printf("response=%v",respMap)
Kind regards,
Dennis
system
(system)
Closed
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.