使用Go语言的GIN框架获取API响应。

huangapple go评论76阅读模式
英文:

GET Api response using Go Lang's GIN

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Go语言和gin框架的新手。
我正在尝试获取下面代码的响应。
请问有人可以指导我犯了什么错误吗?

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("")
}

响应是空的。

这是实际的响应:
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"
}
英文:

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"

}

答案1

得分: 2

根据你的需求,你可能更适合使用httputil.ReverseProxy。但是,这只适用于你不需要处理上游响应或对其进行操作的情况。否则,你需要使用类似ioutil.ReadAll的方法来读取响应体,甚至将其解码为结构体。

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
    }
    
    // 如果没有错误,应该关闭响应体
    defer response.Body.Close()    
     
    // 因此,这个条件移到了自己的代码块中
    if response.StatusCode != http.StatusOK {
        c.Status(http.StatusServiceUnavailable)
        return
    }
    
    // 在你的实际代码中使用适当的结构体类型
    // 空接口只是为了演示
    var v interface{}
    json.NewDecoder(response.Body).Decode(&v)
    fmt.Println("Test", v)

    c.JSON(200, v)
})
英文:

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)
})

答案2

得分: 0

这里定义了一个结构体来绑定响应:

type Responce struct {
    UserID uint   `json:"userId"`
    Id     uint   `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
}

在路由"/foo"上注册了一个处理函数:

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)
})
英文:

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)
})

huangapple
  • 本文由 发表于 2022年2月27日 03:25:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/71279659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定