go web服务(2)

来源:互联网 发布:人口密度数据 编辑:程序博客网 时间:2024/06/07 20:34

练习:HTTP 处理

实现下面的类型,并在其上定义 ServeHTTP 方法。在 web 服务器中注册它们来处理指定的路径。

type String stringtype Struct struct {    Greeting string    Punct    string    Who      string}

例如,可以使用如下方式注册处理方法:

http.Handle("/string", String("I'm a frayed knot."))http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})

package mainimport (    "fmt"    "log"    "net/http")type String stringtype 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))}






0 0
原创粉丝点击