两种方法的实现http请求

我有这个接口,我需要为两个调用实现,


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


守候你守候我
浏览 154回答 1
1回答

SMILET

根据我的评论,不要使用interface.一个简单的struct就足够了:type HealthChecker struct {&nbsp; &nbsp; URL string}func (h HealthChecker) Check() error {&nbsp; &nbsp; resp, err := http.Get(h.URL)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; defer resp.Body.Close()&nbsp; &nbsp; if resp.StatusCode != http.StatusOK {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Errorf("got http status %d instead of %d", resp.StatusCode, http.StatusOK)&nbsp; &nbsp; }&nbsp; &nbsp; return nil}要使用:ex := HealthChecker{"http://example.com/healthz"}log.Println(ex.URL, ex.Check()) // http://example.com/healthz got http status 404 instead of 200g := HealthChecker{"http://google.com/"}log.Println(g.URL, g.Check()) // http://google.com/ <nil>https://play.golang.org/p/ktb2xX7DHKI
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go