在 go 语言中,我们可以给类型增加自定义的方法。下面实验增加ServeHTTP方法。
首先建立两个类型
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
给类型增加 ServeHTTP 方法
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)
}
在 ServeHTTP 前的括号内,就是要增加方法的类型。
在 主函数 main 中写相关的监听。我们定义为使用 4000 端口。
http.Handle("/string", String("I'm a Gopher"))
http.Handle("/struct", &Struct{"Hello", ":", "Gopher!"})
log.Fatal(http.ListenAndServe(":4000", nil))
系统运行后,使用浏览器查看运行效果


完整代码
/**
* myHttp
* @Author: Jian Junbo
* @Email: junbojian@qq.com
* @Create: 2017/10/19 10:35
* Copyright (c) 2017 Jian Junbo All rights reserved.
*
* Description:
*/
package main
import (
"net/http"
"fmt"
"log"
)
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 Gopher"))
http.Handle("/struct", &Struct{"Hello", ":", "Gopher!"})
log.Fatal(http.ListenAndServe(":4000", nil))
}
网友评论