Aditya Malviya
Aditya Malviya

Reputation: 2149

GET Api response using Go Lang's GIN

I'm newbie to go lang and gin framework. I'm trying to get a response of the code below. Can someone pls guide me what mistake I'm doing?

func main() {
router := gin.Default()
router.GET("/foo", func(c *gin.Context) {
    response, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil || response.StatusCode != http.StatusOK {
        c.Status(http.StatusServiceUnavailable)
        return
    }
    reader := response.Body
    fmt.Println("Test", reader)

    c.JSON(200, reader)
})
router.Run("")
}

Response is empty.

This is the actual response curl -X GET "https://jsonplaceholder.typicode.com/posts/1"

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"

}

Upvotes: 0

Views: 4717

Answers (2)

Noushad ibrahim
Noushad ibrahim

Reputation: 1

Here defined a struct to bind reponce type Responce struct { UserID uint json:"userId" Id uint json:"id" Title string json:"title" Body string json:"body" }

r.GET("/foo", func(c *gin.Context) {
    response, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil || response.StatusCode != http.StatusOK {
        c.Status(http.StatusServiceUnavailable)
        return
    }
    var resp Responce

    json.NewDecoder(response.Body).Decode(&resp)
    fmt.Println("Test", resp)

    c.JSON(200, resp)
})

Upvotes: 0

The Fool
The Fool

Reputation: 20547

Depending on what you are doing, you may be better of using httputil.ReverseProxy. But that only works if you don't need to work with the upstream response or manipulate it. Otherwise, you need to read the body with something like ioutil.ReadAll or even decode it into a struct.

router.GET("/foo", func(c *gin.Context) {
    response, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil {
        c.Status(http.StatusServiceUnavailable)
        return
    }
    
    // if there was no error, you should close the body
    defer response.Body.Close()    
     
    // hence this condition is moved into its own block
    if response.StatusCode != http.StatusOK {
        c.Status(http.StatusServiceUnavailable)
        return
    }
    
    // use a proper struct type in your real code
    // the empty interface is just for demonstration
    var v interface{}
    json.NewDecoder(response.Body).Decode(&v)
    fmt.Println("Test", v)

    c.JSON(200, v)
})

Upvotes: 2

Related Questions