From e307b2f706a9043e1572bfce31a2a7f379a35326 Mon Sep 17 00:00:00 2001 From: eduardo Date: Thu, 4 Aug 2022 02:06:55 -0300 Subject: [PATCH] feat(ipfy): add offline response --- src/environment/shell.go | 15 ++++++++++++++- src/segments/ipify.go | 6 ++++++ src/segments/ipify_test.go | 12 ++++++++++-- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/environment/shell.go b/src/environment/shell.go index 07b8bfab..dbfea3f9 100644 --- a/src/environment/shell.go +++ b/src/environment/shell.go @@ -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 { diff --git a/src/segments/ipify.go b/src/segments/ipify.go index 6e139a63..9aefa4aa 100644 --- a/src/segments/ipify.go +++ b/src/segments/ipify.go @@ -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 } diff --git a/src/segments/ipify_test.go b/src/segments/ipify_test.go index f701f11d..95575e95 100644 --- a/src/segments/ipify_test.go +++ b/src/segments/ipify_test.go @@ -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 {