Skip to content

Instantly share code, notes, and snippets.

@mcluseau
Last active September 1, 2018 18:38
Show Gist options
  • Save mcluseau/1c20c3973fa3acb544d0505637be8d67 to your computer and use it in GitHub Desktop.
Save mcluseau/1c20c3973fa3acb544d0505637be8d67 to your computer and use it in GitHub Desktop.
// update of
// https://groups.google.com/d/msg/golang-nuts/UwH5CreZPe4/xxI8gFsVBAAJ
// in reaction to
// https://go.googlesource.com/proposal/+/master/design/go2draft-error-handling-overview.md
/*
Instead of "when", use the proposed syntax to reduce ambiguity and allow more complex use cases.
It may be nice to be able to type handlers too, like `handle err error { ... }`
*/
var ProtocolError = errors.New("protocol error")
type Remote interface {
Read() (msg string, err error)
Sent(msg string) (err error)
Close()
}
func chatWithRemote(remote Remote) error {
handle readErr {
return fmt.Errorf("failed to read: %v", readErr)
}
handle writeErr {
return fmt.Errorf("failed to send: %v", writeErr)
}
msg, check readErr := remote.Read()
if msg != "220 test.com ESMTP Postfix" {
return ProtocolError
}
check writeErr = remote.Sent("EHLO example.com")
handle readErr {
// failed reads will make remote unusable anymore
remote.Sent("QUIT")
remote.Close()
}
for {
msg, check readErr := remote.Read()
if msg == "250 DSN" {
break
}
}
check writeErr = remote.Sent("QUIT")
}
// Original example will look like that instead:
func CopyFile(src, dst string) error {
handle err {
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
r, check err := os.Open(src)
defer r.Close()
w, check err := os.Create(dst)
handle err {
w.Close()
os.Remove(dst) // (only if a check fails)
}
check err = io.Copy(w, r)
check err = w.Close()
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment