Created
October 11, 2018 22:29
-
-
Save rifki/acb2cbd18b3b15766e34779ca0f08f50 to your computer and use it in GitHub Desktop.
JSON Unmarshal into struct Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// JSON Unmarshal into struct Example | |
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"github.com/gin-gonic/gin" | |
) | |
const trendingURL = "https://lapi.kumparan.com/v3.0/trending/topics" | |
type TrendingData struct { | |
Code int | |
Page int | |
Limit int | |
Total int | |
Results []struct { | |
_Key string | |
Author struct { | |
Id string | |
Name string | |
Username string | |
} | |
Date struct { | |
Create string | |
} | |
Description string | |
Flag struct{} | |
Name string | |
Slug string | |
Status string | |
Type string | |
Url string | |
User struct{} | |
Statistic struct { | |
Followers int | |
} | |
Position bool | |
_Id string | |
_Rev string | |
} | |
} | |
func main() { | |
route := gin.Default() | |
route.GET("/", func(c *gin.Context) { | |
page := c.Query("page") | |
limit := c.Query("limit") | |
res, _ := http.Get(trendingURL + "?limit=" + limit + "&page=" + page) | |
body, _ := ioutil.ReadAll(res.Body) | |
var trendingData TrendingData | |
err := json.Unmarshal(body, &trendingData) | |
if err != nil { | |
fmt.Println("There was an error bro! : ", err) | |
panic(err) | |
} | |
if trendingData.Code == 200 { | |
for i := 0; i < trendingData.Limit; i++ { | |
var desc = trendingData.Results[i].Description | |
var urlDetail = "https://kumparan.com/topic/" + trendingData.Results[i].Slug | |
var content = fmt.Sprintf("%s %s", desc, urlDetail) | |
fmt.Println(content) | |
} | |
} else { | |
fmt.Println("There was an error status code : ", trendingData.Code) | |
} | |
if trendingData.Code == 200 { | |
c.JSON(http.StatusBadGateway, gin.H{ | |
"data": trendingData.Results, | |
}) | |
} else { | |
c.JSON(http.StatusBadGateway, gin.H{ | |
"results": "Website Down!", | |
}) | |
} | |
}) | |
route.Run(":8000") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: