Lingkang的go学习日记1

起因

无意刷到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)
// ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值