51 lines
839 B
Go
51 lines
839 B
Go
package basic_http
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type Service struct {
|
|
ServiceName string
|
|
Url string
|
|
Headers http.Header
|
|
}
|
|
|
|
func (s Service) Name() string {
|
|
return s.ServiceName
|
|
}
|
|
|
|
func (s Service) Lookup() (net.IP, error) {
|
|
req, err := http.NewRequest("GET", s.Url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req.Header = s.Headers
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return nil, fmt.Errorf("HTTP Response: %s", resp.Status)
|
|
}
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Trim spaces and stuff.
|
|
ip_str := strings.TrimSpace(string(body))
|
|
|
|
ip := net.ParseIP(ip_str)
|
|
if ip == nil {
|
|
err = fmt.Errorf("Failed to parse ip: %s", ip_str)
|
|
}
|
|
return ip, err
|
|
}
|