Convert python to golang

ı 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:

  1. make a GET request to a service
  2. prints some info
  3. iterates over the results
  4. downloads the avatars and save theme to the disk.

what do you tried so far ?

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.