1、
// error
import (
"fmt"
"time"
)
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string { // 该函数意味MyError实现了error接口(内建)
return fmt.Sprintf("at %v, %s",
e.When, e.What)
}
func run() error {
return &MyError{
time.Now(),
"it didn't work",
}
}
func main() {
if err := run(); err != nil {
fmt.Println(err) //输出同下,这和内部实现有关吧
// fmt.Println(err.Error())
}
}
2、reader
import (
"fmt"
"io"
"strings"
)
func main() {
r := strings.NewReader("Hello, Reader!")
b := make([]byte, 8)
fmt.Println(b)
for {
n, err := r.Read(b)
fmt.Printf("n = %v err = %v b = %v\n", n, err, b)
fmt.Printf("b[:n] = %q\n", b[:n])
if err == io.EOF {
break
}
}
/*
n = 8 err = <nil> b = [72 101 108 108 111 44 32 82]
b[:n] = "Hello, R"
n = 6 err = <nil> b = [101 97 100 101 114 33 32 82]
b[:n] = "eader!"
n = 0 err = EOF b = [101 97 100 101 114 33 32 82]
b[:n] = ""
*/
}
2.1、
type rot13Reader struct {
r io.Reader
}
func (rot13 *rot13Reader) Read(b []byte) (int, error) {
return (*rot13).r.Read(b)
}
func testReader2() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
3、web server
import (
"fmt"
"log"
"net/http"
)
type Hello struct{}
func (h Hello) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, "Hello!")
}
func main() {
var h Hello
err := http.ListenAndServe("localhost:4000", h)
if err != nil {
log.Fatal(err)
}
}
包 http 通过任何实现了 http.Handler 的值来响应 HTTP 请求:
package http
type Handler interface {
ServeHTTP(w ResponseWriter, r *Request)
}
3.1、
import (
"fmt"
"log"
"net/http"
)
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
func (str String) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, str)
}
func (s *Struct) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, fmt.Sprintf("%v%v%v", (*s).Greeting, (*s).Punct,
(*s).Who))
}
func testWebServer2() {
// str := String("I'm a frayed knot.")
str := String("hello world")
s := &Struct{"Hello", ":", "Gophers!"}
http.Handle("/string", str) // 注册处理方法
http.Handle("/struct", s)
log.Fatal(http.ListenAndServe("localhost:4000", nil))
}