diff options
Diffstat (limited to 'service.go')
| -rw-r--r-- | service.go | 92 |
1 files changed, 87 insertions, 5 deletions
@@ -3,10 +3,92 @@ package lilin +import ( + "fmt" + "log" + "net" + "net/http" + + "git.sr.ht/~shulhan/lilin/internal" +) + type Service struct { - Name string - Type string `ini:"::type"` - Method string `ini:"::method"` - Address string `ini:"::address"` - Timeout string `ini:"::timeout"` + httpConn *http.Client + dialer *net.Dialer + opts ServiceOptions + isReady bool +} + +// NewService create and initialize the connection to service. +func NewService(opts ServiceOptions) (svc *Service, err error) { + svc = &Service{ + opts: opts, + } + err = svc.opts.init() + if err != nil { + return nil, fmt.Errorf(`NewService: %w`, err) + } + return svc, nil +} + +// Scan the service for availability. +func (svc *Service) Scan() (report ScanReport) { + var err error + + report.At = internal.Now() + if !svc.isReady { + err = svc.connect() + if err != nil { + report.Error = err.Error() + return report + } + } + + switch svc.opts.scanURL.Scheme { + case serviceKindHTTP, serviceKindHTTPS: + var req = &http.Request{ + Method: svc.opts.HTTPMethod, + URL: svc.opts.scanURL, + } + var httpResp *http.Response + httpResp, err = svc.httpConn.Do(req) + if err != nil { + report.Error = err.Error() + return report + } + if httpResp.StatusCode != 200 { + report.Error = httpResp.Status + return report + } + + case serviceKindTCP, serviceKindUDP: + var conn net.Conn + conn, err = svc.dialer.Dial(`udp`, svc.opts.scanURL.Host) + if err != nil { + report.Error = err.Error() + return report + } + err = conn.Close() + if err != nil { + log.Printf(`Scan: Close: %s`, err) + } + } + report.Success = true + return report +} + +func (svc *Service) connect() (err error) { + switch svc.opts.scanURL.Scheme { + case serviceKindHTTP, serviceKindHTTPS: + svc.httpConn = &http.Client{ + Timeout: svc.opts.timeout, + } + + case serviceKindTCP, serviceKindUDP: + svc.dialer = &net.Dialer{ + Timeout: svc.opts.timeout, + } + } + svc.isReady = true + return nil } |
