亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

兩種方法的實現http請求

兩種方法的實現http請求

Go
守候你守候我 2022-07-04 16:38:57
我有這個接口,我需要為兩個調用實現,1.   req, err := http.NewRequest("GET", "http://example.com/healthz", nil)2. req, err := http.NewRequest("GET", "http://localhost:8082/rest/foos/9", nil) 但是接口使用的是reqof類型的*http.Request方法,我該怎么做呢?type HealthChecker interface {    Name() string    Check(req *http.Request) error}type ping struct{}func (p ping) Check(req *http.Request) error { }func (ping) Name() string {    return "check1"}https://play.golang.org/p/PvpKD-_MFRS
查看完整描述

1 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

根據我的評論,不要使用interface.


一個簡單的struct就足夠了:


type HealthChecker struct {

    URL string

}


func (h HealthChecker) Check() error {

    resp, err := http.Get(h.URL)

    if err != nil {

        return err

    }

    defer resp.Body.Close()


    if resp.StatusCode != http.StatusOK {

        return fmt.Errorf("got http status %d instead of %d", resp.StatusCode, http.StatusOK)

    }


    return nil

}

要使用:


ex := HealthChecker{"http://example.com/healthz"}


log.Println(ex.URL, ex.Check()) // http://example.com/healthz got http status 404 instead of 200



g := HealthChecker{"http://google.com/"}


log.Println(g.URL, g.Check()) // http://google.com/ <nil>

https://play.golang.org/p/ktb2xX7DHKI


查看完整回答
反對 回復 2022-07-04
  • 1 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號