diff options
Diffstat (limited to 'service_options.go')
| -rw-r--r-- | service_options.go | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/service_options.go b/service_options.go new file mode 100644 index 0000000..957987a --- /dev/null +++ b/service_options.go @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: 2025 M. Shulhan <ms@kilabit.info> +// SPDX-License-Identifier: GPL-3.0-only + +package lilin + +import ( + "fmt" + "net" + "net/http" + "net/url" + "strings" + "time" +) + +const ( + serviceKindHTTP = `http` + serviceKindHTTPS = `https` + serviceKindTCP = `tcp` + serviceKindUDP = `udp` +) + +type ServiceOptions struct { + scanURL *url.URL + + Name string + + // The Address of service, using scheme based, for example + // - http://example.com/health for HTTP service, + // - tcp://127.0.0.1:22 for TCP service, + // - udp://127.0.0.1:53 for UDP service. + Address string `ini:"::address"` + + // HTTPMethod define HTTP method to be used to scan the HTTP service. + // Valid value is either DELETE, GET, HEAD, PATCH, POST, or PUT. + HTTPMethod string `ini:"::method"` + + // Timeout for connecting and reading response from service. + Timeout string `ini:"::timeout"` + + timeout time.Duration +} + +func (opts *ServiceOptions) init() (err error) { + opts.scanURL, err = url.Parse(opts.Address) + if err != nil { + return fmt.Errorf(`invalid address %s`, opts.Address) + } + + var scheme = strings.ToLower(opts.scanURL.Scheme) + switch scheme { + case `http`, `https`: + var httpMethod = strings.ToUpper(opts.HTTPMethod) + switch httpMethod { + case ``: + opts.HTTPMethod = http.MethodGet + case http.MethodDelete, http.MethodGet, http.MethodHead, + http.MethodOptions, http.MethodPatch, http.MethodPost, + http.MethodPut: + opts.HTTPMethod = httpMethod + default: + return fmt.Errorf(`invalid HTTP method %s`, opts.HTTPMethod) + } + + case serviceKindTCP: + _, err = net.ResolveTCPAddr(scheme, opts.scanURL.Host) + if err != nil { + return fmt.Errorf(`invalid TCP address %s`, opts.Address) + } + + case serviceKindUDP: + _, err = net.ResolveUDPAddr(scheme, opts.scanURL.Host) + if err != nil { + return fmt.Errorf(`invalid UDP address %s`, opts.Address) + } + + default: + return fmt.Errorf(`unknown scheme in address %s`, scheme) + } + + if len(opts.Timeout) == 0 { + opts.timeout = defTimeout + } else { + opts.timeout, err = time.ParseDuration(opts.Timeout) + if err != nil { + return fmt.Errorf(`invalid Timeout %s`, opts.Timeout) + } + } + return nil +} |
