go http学习笔记

2018-06-01  本文已影响0人  浅吟风至圣

go http学习笔记

@[goweb, go, http]

1.go http基础

package main
import (
    "net/http"
    "io"
)
func helloHandler(w http.ResponseWriter,req *http.Request)  {
    io.WriteString(w,"hello,world!\n")
}
func main()  {
    http.HandleFunc("/",helloHandler)
    http.ListenAndServe(":12345",nil)
}
type Handler interface{
    ServeHTTP(ResponseWriter,*Request)
}

只要实现了ServeHTTP方法的类型都可以作为handler

func helloHandler(w ResponseWriter,res *Request){
    io.WriteString(w,"hello,world!\n")
}
func main(){
    http.HandleFunc("/",helloHandler)
    http.ListenAndServe(":12345",nil)
}

main函数中的部分也可以写成:

hh:=http.HandlerFunc(helloHandler)
http.Handle("/",hh)
http.ListenAndServe(":12345",nil)

2.路由

net/http有一个很重要的概念ServeMuxMuxMultiplexor的缩写,意思就是多路传输(请求传过来,根据某种判断,分流到后端多个不同的地方。ServeMux可以注册多个URL和Handler的对应关系,并自动把请求转发到对应的handler进行处理。比如用户请求的URL是/hello就返回hello,world,否则就返回用户的路径,路径是从请求对象http.Requests中提取的。实现如下:

package main
import(
    "io"
    "net/http"
)
func helloHandler(w http.ResponseWriter,res *http.Request){
    io.WriteString(w,"Hello,World!\n")
}
func echoHandler(w http.ResponseWriter,res *http.Request){
    io.WriteString(w,res.URL.Path)
}
func main(){
    mux:=http.NewServeMux()//通过NewServeMux生成了SerMux结构,URL和handler是通过它注册的
    mux.HandleFunc("/hello",helloHandler)
    mux.HandleFunc("/",echoHandler)
    http.ListenAndServe(":12345",mux)//ServeMux也是handler接口的实现,这里的mux也是Handler类
}

关于ServerMux,有几点要说明:

以上基本涵盖了构建HTTP服务端的所有内容,基本不超出这个范围,其他的就是和语言无关的网络基础了。

上一篇 下一篇

猜你喜欢

热点阅读