两种方法实现http请求
Implent http request for two methods
我有这个接口需要实现两次调用,
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"
}
根据我的意见,不要 over-complicate 使用 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>
我有这个接口需要实现两次调用,
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"
}
根据我的意见,不要 over-complicate 使用 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>