深入理解Golang之http server

构建服务器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支持函数类型的变量和赋值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值