forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example4.go
93 lines (78 loc) · 1.85 KB
/
example4.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// http://play.golang.org/p/6GYqwSxHjI
// Package example5 provides code to show how to implement behavior as context.
package example5
import (
"bufio"
"fmt"
"io"
"log"
"net"
)
// client represents a single connection in the room.
type client struct {
name string
reader *bufio.Reader
}
// TypeAsContext shows how to check multiple types of possible custom error
// types that can be returned from the net package.
func (c *client) TypeAsContext() {
for {
line, err := c.reader.ReadString('\n')
if err != nil {
switch e := err.(type) {
case *net.OpError:
if !e.Temporary() {
log.Println("Temporary: Client leaving chat")
return
}
case *net.AddrError:
if !e.Temporary() {
log.Println("Temporary: Client leaving chat")
return
}
case *net.DNSConfigError:
if !e.Temporary() {
log.Println("Temporary: Client leaving chat")
return
}
default:
if err == io.EOF {
log.Println("EOF: Client leaving chat")
return
}
log.Println("read-routine", err)
}
}
fmt.Println(line)
}
}
// temporary is declared to test for the existence of the method coming
// from the net package.
type temporary interface {
Temporary() bool
}
// BehaviorAsContext shows how to check for the behavior of an interface
// that can be returned from the net package.
func (c *client) BehaviorAsContext() {
for {
line, err := c.reader.ReadString('\n')
if err != nil {
switch e := err.(type) {
case temporary:
if !e.Temporary() {
log.Println("Temporary: Client leaving chat")
return
}
default:
if err == io.EOF {
log.Println("EOF: Client leaving chat")
return
}
log.Println("read-routine", err)
}
}
fmt.Println(line)
}
}