构建服务器1.go
package main
import (
"fmt"
"net/http"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world") // 前端输出
}
func main () {
http.HandleFunc("/",indexHandler) // 根据“/”路由执行注册的函数
http.ListenAndServe(":8080",nil)
}
构建服务器2.go
package main
import (
"fmt"
"net/http"
)
type indexHandler struct {
content string
}
func (i *indexHandler) ServeHTTP(w http.ResponseWriter,r *http.Request) {
fmt.Fprintf(w,i.content)
}
func main () {
http.Handle("/", &indexHandler{content:"hello world"}) // 根据“/”路由执行注册的对象
http.ListenAndServe(":8081",nil)
}
总结区别:
在构建服务器1中的func main函数中 http.HandleFunc("/",indexHandleFunc) // 注册函数
在构建服务器2中的func main函数中 http.Handle("/",&indexHandle{content:"hello world"}) // 注册对象
一个是HandleFunc 一个是Handle 矿建里面用的是handle
两个都是首先注册路由,然后创建服务并开启监听即可,根据路由执行对应的函数或者是方法
一个函数的签名就是他们的参数类型和返回值类型,是一个函数与使用环境的界面,跟函数名字无关。
相同签名的函数是同一类型的,相同类型的变量才可以赋值,go支持函数类型的变量和赋值。