2021-12-23 05:58:18 -08:00
|
|
|
package main
|
|
|
|
|
2022-01-26 01:23:18 -08:00
|
|
|
import "oh-my-posh/environment"
|
|
|
|
|
2021-12-23 05:58:18 -08:00
|
|
|
type ipify struct {
|
2022-01-01 11:08:08 -08:00
|
|
|
props Properties
|
2022-01-26 01:23:18 -08:00
|
|
|
env environment.Environment
|
2021-12-23 05:58:18 -08:00
|
|
|
IP string
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
IpifyURL Property = "url"
|
|
|
|
)
|
|
|
|
|
2022-01-23 12:37:51 -08:00
|
|
|
func (i *ipify) template() string {
|
|
|
|
return "{{ .IP }}"
|
|
|
|
}
|
|
|
|
|
2021-12-23 05:58:18 -08:00
|
|
|
func (i *ipify) enabled() bool {
|
|
|
|
ip, err := i.getResult()
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
i.IP = ip
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *ipify) getResult() (string, error) {
|
|
|
|
cacheTimeout := i.props.getInt(CacheTimeout, DefaultCacheTimeout)
|
|
|
|
|
|
|
|
url := i.props.getString(IpifyURL, "https://api.ipify.org")
|
|
|
|
|
|
|
|
if cacheTimeout > 0 {
|
|
|
|
// check if data stored in cache
|
2022-01-23 12:37:51 -08:00
|
|
|
val, found := i.env.Cache().Get(url)
|
2021-12-23 05:58:18 -08:00
|
|
|
// we got something from te cache
|
|
|
|
if found {
|
|
|
|
return val, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
httpTimeout := i.props.getInt(HTTPTimeout, DefaultHTTPTimeout)
|
|
|
|
|
2022-01-07 10:41:58 -08:00
|
|
|
body, err := i.env.HTTPRequest(url, httpTimeout)
|
2021-12-23 05:58:18 -08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// convert the body to a string
|
|
|
|
response := string(body)
|
|
|
|
|
|
|
|
if cacheTimeout > 0 {
|
|
|
|
// persist public ip in cache
|
2022-01-23 12:37:51 -08:00
|
|
|
i.env.Cache().Set(url, response, cacheTimeout)
|
2021-12-23 05:58:18 -08:00
|
|
|
}
|
|
|
|
return response, nil
|
|
|
|
}
|
|
|
|
|
2022-01-26 01:23:18 -08:00
|
|
|
func (i *ipify) init(props Properties, env environment.Environment) {
|
2021-12-23 05:58:18 -08:00
|
|
|
i.props = props
|
|
|
|
i.env = env
|
|
|
|
}
|