练习:HTTP 处理
实现下面的类型,并在其上定义 ServeHTTP 方法。在 web 服务器中注册它们来处理指定的路径。
type String string type Struct struct { Greeting string Punct string Who string }
例如,可以使用如下方式注册处理方法:
http.Handle("/string", String("I'm a frayed knot.")) http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
package main import ( "fmt" "log" "net/http" ) type String string type Struct struct { Greeting string Punct string Who string } func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, s) } func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, s) } func main() { http.Handle("/string", String("I'm a frayed knot.")) http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"}) log.Fatal(http.ListenAndServe("localhost:4000", nil)) }
有疑问加站长微信联系(非本文作者)