赞
踩
包 http 通过任何实现了 http.Handler 的值来响应 HTTP 请求:
- package http
-
- type Handler interface {
- ServeHTTP(w ResponseWriter, r *Request)
- }
在下边例子中,类型 Hello 实现了 http.Handler。
访问 http://localhost:4000/ 会看到程序的打印输出。
- package main
-
- 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)
- }
- }
- package main
- import (
- "fmt"
- "log"
- "net/http"
- )
- type String string
- type Struct struct {
- Greeting string
- Punct string
- Who string
- }
- //此方法配合http.Handle("/string", String("I'm a frayed knot."))使用
- func (h String) ServeHTTP(
- w http.ResponseWriter,
- r *http.Request) {
- fmt.Fprint(w, h)
- }
- //此方法配合http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})使用
- /*func (h *Struct) ServeHTTP(
- w http.ResponseWriter,
- r *http.Request) {
- fmt.Fprint(w, h)
- }*/
-
- func main() {
- http.Handle("/string", String("I'm a frayed knot."))
- // http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
- // your http.Handle calls here
- log.Fatal(http.ListenAndServe("localhost:4000", nil))
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。