feat(ipfy): add offline response

This commit is contained in:
eduardo 2022-08-04 02:06:55 -03:00 committed by Jan De Dobbeleer
parent 5f063e80f3
commit e307b2f706
3 changed files with 30 additions and 3 deletions

View file

@ -587,6 +587,19 @@ func (env *ShellEnvironment) Shell() string {
return env.CmdFlags.Shell
}
func (env *ShellEnvironment) unWrapError(err error) error {
cause := err
for {
type nested interface{ Unwrap() error }
unwrap, ok := cause.(nested)
if !ok {
break
}
cause = unwrap.Unwrap()
}
return cause
}
func (env *ShellEnvironment) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...HTTPRequestModifier) ([]byte, error) {
defer env.Trace(time.Now(), "HTTPRequest", targetURL)
ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
@ -605,7 +618,7 @@ func (env *ShellEnvironment) HTTPRequest(targetURL string, body io.Reader, timeo
response, err := client.Do(request)
if err != nil {
env.Log(Error, "HTTPRequest", err.Error())
return nil, err
return nil, env.unWrapError(err)
}
// anything inside the range [200, 299] is considered a success
if response.StatusCode < 200 || response.StatusCode >= 300 {

View file

@ -1,6 +1,7 @@
package segments
import (
"net"
"oh-my-posh/environment"
"oh-my-posh/properties"
)
@ -13,6 +14,8 @@ type IPify struct {
const (
IpifyURL properties.Property = "url"
OFFLINE = "OFFLINE"
)
func (i *IPify) Template() string {
@ -46,6 +49,9 @@ func (i *IPify) getResult() (string, error) {
httpTimeout := i.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
body, err := i.env.HTTPRequest(url, nil, httpTimeout)
if dnsErr, OK := err.(*net.DNSError); OK && dnsErr.IsNotFound {
return OFFLINE, nil
}
if err != nil {
return "", err
}

View file

@ -2,6 +2,7 @@ package segments
import (
"errors"
"net"
"oh-my-posh/mock"
"oh-my-posh/properties"
"testing"
@ -36,11 +37,18 @@ func TestIpifySegment(t *testing.T) {
Template: "Ext. IP: {{.IP}}",
},
{
Case: "Error in retrieving data",
Case: "Network Error",
Response: "nonsense",
Error: errors.New("Something went wrong"),
ExpectedString: "",
Error: errors.New("network is unreachable"),
ExpectedEnabled: false,
},
{
Case: "Offline",
ExpectedString: OFFLINE,
Error: &net.DNSError{IsNotFound: true},
ExpectedEnabled: true,
},
}
for _, tc := range cases {