Noob’s web server questions

Written by
Link to Post by 

Hey all, I’m starting a small project that uses a third parties API, and figured it would be a good time to finally dive into Go. I’m consuming JSON from a third party API with Go, and am serving it back to the front end. This conceptually makes sense to me but trying to find the right keywords to search for examples is tough.

browser GET request to Go web server -> Go GET request to third party API -> Go serves json to browser

here’s the very simplified code

func getData(w http.ResponseWriter, r *http.Request) { url := "" req, _ := http.NewRequest("GET", url, nil) client := &http.Client{} resp, _ := client.Do(req) w.Header().Set("Content-type", "application/json") defer resp.Body.Close() // Method one io.Copy(w, resp.Body) // Method two var data map[string]interface{} json.NewDecoder(resp.Body).Decode(&data) js, _ := json.Marshal(data) w.Write(js) } 

Both method one and two work, but I’m wondering if ones more preferred? My current goal is simply to just echo the JSON response to the frontend

Also, is it normal to build a struct to match every API calls response format? I’m currently just using a map in method two, it seems kinda cumbersome to build a struct for all the API calls I’d make from the backend

Let me know if I’m misunderstanding something conceptually and going about this wrong way, thank you!

submitted by /u/SavageFerret
[link] [comments]

Article Tags:
· ·
Article Categories:

Leave a Reply