-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
51 lines (40 loc) · 1.11 KB
/
main.go
File metadata and controls
51 lines (40 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"encoding/json"
"net/http"
"github.com/gin-gonic/gin"
)
// type struct
type ExternalAPIResponse struct {
One string `json:"one"`
Key string `json:"key"`
}
func main() {
r := gin.Default()
r.GET("/call-external-api", func(c *gin.Context) {
externalAPIURL := "http://echo.jsontest.com/key/value/one/two"
req, err := http.NewRequest("GET", externalAPIURL, nil)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create request"})
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to call external API"})
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
c.JSON(resp.StatusCode, gin.H{"error": "Received non-OK response from external API"})
return
}
var apiResponse ExternalAPIResponse
if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to decode response"})
return
}
c.JSON(http.StatusOK, apiResponse)
})
r.Run(":8080")
}