紧急的http请求两种方法

时间:2020-09-29 13:42:53

标签: go interface

我有这个接口,需要实现两次通话

1.   req, err := http.NewRequest("GET", "http://example.com/healthz", nil)
2. req, err := http.NewRequest("GET", "http://localhost:8082/rest/foos/9", nil) 

但是接口使用的是req类型的*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 个答案:

答案 0 :(得分:1)

根据我的评论,请不要使用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