Go Web --- 搭建服务器
server_1.go 单处理器(多路复用器)
package main
import (
"fmt"
"net/http"
)
type DefaultHandler struct{}
func (dh *DefaultHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "welcome")
}
func main() {
dh := DefaultHandler{}
server := http.Server{
Addr: "127.0.0.1:8081",
Handler: &dh,//单处理器,所有请求都会使用这个处理器
}
server.ListenAndServe()
}
server_2.go 使用多处理器
package main
import (
"fmt"
"net/http"
)
type IndexHandler struct{}
type ListHandler struct{}
func (ih *IndexHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "this is index")
}
func (lh *ListHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "this is list")
}
func main() {
ih := IndexHandler{}
lh := ListHandler{}
server := http.Server{
Addr: "127.0.0.1:8081",
}
http.Handle("/index", &ih)
http.Handle("/list", &lh)
server.ListenAndServe()
}
server_3.go 使用处理器函数
package main
import (
"fmt"
"net/http"
)
func index(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "this is index page")
}
func list(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "this is list page")
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8081",
}
http.HandleFunc("/index", index)
http.HandleFunc("/list", list)
server.ListenAndServe()
}
注意,在绑定路由的时候,假设监听localhost:80,下面的case对于Handle和HandleFunc同样适用。
前提:假设都只绑定了代码中的那些处理器。
case 1
http.HandleFunc("/index",index)
访问localhost/index 调用的是index控制器。
访问localhost/index/ 404
访问localhost/index/aaa 404
case 2
http.HandleFunc("/index/",index)
使用index控制器的情况:
访问localhost/index
访问localhost/index/
访问localhost/index/aaa
case 3
http.HandleFunc("/index/",index)
http.HandleFunc("/index/list",list)
使用index控制器的情况:
1、访问localhost/index
2、访问localhost/index/
3、访问localhost/index/aaa
4、访问localhost/index/aaa/
5、访问localhost/index/list/
使用list控制器的情况:
1、访问localhost/index/list
如需转载,请注明文章出处,谢谢!!!
浙公网安备 33010602011771号