码迷,mamicode.com
首页 > Web开发 > 详细

A Tour of Go Exercise: HTTP Handlers

时间:2014-10-28 23:51:10      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   for   sp   div   on   

Implement the following types and define ServeHTTP methods on them. Register them to handle specific paths in your web server.

type String string

type Struct struct {
    Greeting string
    Punct    string
    Who      string
}

For example, you should be able to register handlers using:

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


package main

import (
    "net/http"
    "fmt"
)
type String string

type Struct struct {
    Greeting string
    Punct    string
    Who      string
}


func (h Struct) ServeHTTP(
    w http.ResponseWriter,
    r *http.Request) {
    fmt.Fprint(w, h)
}
func (s String) 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!"})
    // your http.Handle calls here
    http.ListenAndServe("localhost:4000", nil)

}

 

A Tour of Go Exercise: HTTP Handlers

标签:style   blog   http   color   os   for   sp   div   on   

原文地址:http://www.cnblogs.com/ghgyj/p/4058214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!