oh-my-posh/src/segments/ipify.go

67 lines
1.2 KiB
Go
Raw Normal View History

2022-01-26 06:54:36 -08:00
package segments
import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
2022-01-26 05:10:18 -08:00
type IPify struct {
props properties.Properties
env environment.Environment
IP string
}
const (
IpifyURL properties.Property = "url"
)
func (i *IPify) Template() string {
2022-02-01 05:07:58 -08:00
return " {{ .IP }} "
}
func (i *IPify) Enabled() bool {
ip, err := i.getResult()
if err != nil {
return false
}
i.IP = ip
return true
}
2022-01-26 05:10:18 -08:00
func (i *IPify) getResult() (string, error) {
2022-07-15 04:24:56 -07:00
cacheTimeout := i.props.GetInt(properties.CacheTimeout, properties.DefaultCacheTimeout)
2022-01-26 04:09:21 -08:00
url := i.props.GetString(IpifyURL, "https://api.ipify.org")
if cacheTimeout > 0 {
// check if data stored in cache
val, found := i.env.Cache().Get(url)
// we got something from te cache
if found {
return val, nil
}
}
2022-07-15 04:24:56 -07:00
httpTimeout := i.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
2022-07-17 12:11:23 -07:00
body, err := i.env.HTTPRequest(url, nil, httpTimeout)
if err != nil {
return "", err
}
// convert the body to a string
response := string(body)
if cacheTimeout > 0 {
// persist public ip in cache
i.env.Cache().Set(url, response, cacheTimeout)
}
return response, nil
}
func (i *IPify) Init(props properties.Properties, env environment.Environment) {
i.props = props
i.env = env
}