英文:
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)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论