起因
无意刷到Hackerrank一道简单题目,发现用到go http包但是不太清楚用法,耽误了点时间,于是专门写一篇关于http的使用,和这道题目解法分享
hackrank题目
Top articles
/* * Complete the 'topArticles' function below. * * The function is expected to return a STRING_ARRAY. * The function accepts INTEGER limit as parameter. * base url for copy/paste: * https://jsonmock.hackerrank.com/api/articles?page=<pageNumber> */
原题目请在hackerrank搜一下,大概意思就是用http协议进行交互,json格式获取参数,一些需求处理
type JsonRespnse struct {
Page int `json:"page"`
Perpage int `json:"per_page"`
Total int `json:"total"`
TotoalPages int `json:"total_pages"`
Data []Records `json:"data"`
}
type Records struct {
Title string `json:"title"`
StoryTitle string `json:"story_title"`
NumComments int `json:"num_comments"`
}
type OrderByRecords []Records
func (a OrderByRecords) Len() int { return len(a) }
func (a OrderByRecords) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a OrderByRecords) Less(i, j int) bool {
if a[i].NumComments == a[j].NumComments {
return strings.Compare(a[i].Title, a[j].Title) == -1
} else {
return a[i].NumComments > a[j].NumComments
}
}
func topArticles(limit int32) []string {
resp, _ := http.Get("https://jsonmock.hackerrank.com/api/articles?page=1")
//respMap := ParseResponse(resp)
body, _ := ioutil.ReadAll(resp.Body)
res := JsonRespnse{
Page: 0,
Perpage: 0,
Total: 0,
TotoalPages: 0,
Data: make([]Records, 0),
}
json.Unmarshal(body, &res)
//fmt.Println(res)
result := make([]Records, 0)
// get all resut
for i := 1; i <= res.TotoalPages; i++ {
resp, _ = http.Get("https://jsonmock.hackerrank.com/api/articles?page=" + strconv.Itoa(i))
bodyi, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(bodyi, &res)
for _, r := range res.Data {
if r.Title == "" && r.StoryTitle == "" {
continue
}
if r.Title == "" {
r.Title = r.StoryTitle
}
result = append(result, r)
}
}
// fmt.Println(result)
// sort
sort.Sort(OrderByRecords(result))
// output
finalResult := make([]string, limit)
for i := 0; i < int(limit); i++ {
if result[i].Title == "" {
finalResult[i] = result[i].StoryTitle
} else {
finalResult[i] = result[i].Title
}
}
fmt.Println(finalResult)
return finalResult
}
go_http包浅析
a. http协议是什么
b. go包中基于get,post,postform
resp, err := http.Get("http://example.com/") ... resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) ... resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})
The caller must close the response body when finished with it:
resp, err := http.Get("http://example.com/") if err != nil { // handle error } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) // ...