golang基础知识总结(5)
使用Go语言搭建一个简单的web服务Demo
在Go语言的源码中就有关于简单的web服务Demo,如下:
// hello world, the web server
package main
import (
"io"
"net/http"
"log"
)
func HelloServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n") } func main() { http.HandleFunc("/hello", HelloServer) //设置访问路径 log.Fatal(http.ListenAndServe(":12345", nil)) }
访问地址:localhost:12345/hello 在浏览器页面就会出现 hello, world! 的字样。
认识Go语言web服务的原理:
server的源码包在:安装路径下/src/net/http/server.go
由main函数中可以看出,起关键作用的函数是: ListenAndServe ,下面是源码中的定义:
// ListenAndServe always returns a non-nil error. //总是返回一个非空的error func ListenAndServe(addr string, handler Handler) error { server := &Server{Addr: addr, Handler: handler} //定义并初始化了一个结构体 return server.ListenAndServe() }
让我们来看看 server 结构体中的定义:
type Server struct { Addr string //用于监听的TCP地址 Handler Handler // 处理程序对HTTP请求做出的响应 TLSConfig *tls.Config // 可选的TLS配置 ReadTimeout time.Duration //读超时 ReadHeaderTimeout time.Duration //允许读取的时间 WriteTimeout time.Duration //写超时 IdleTimeout time.Duration //等待时间最长的时间 MaxHeaderBytes int //最大字节数 TLSNextProto map[string]func(*Server, *tls.Conn, Handler) ConnState func(net.Conn, ConnState) //ConnState指定一个可选的回调函数当客户端连接更改状态时调用。看到ConnState类型和相关常量的细节。 ErrorLog *log.Logger //ErrorLog为错误接受指定一个可选的日志记录器连接和来自处理程序的意外行为。如果nil,日志记录到操作系统。通过日志包的Stderr标准日志记录器。 disableKeepAlives int32 // 自动访问 inShutdown int32 // 以原子方式访问,非零表示处于关闭状态 nextProtoOnce sync.Once // guards setupHTTP2_* init nextProtoErr error // result of http2.ConfigureServer if used mu sync.Mutex listeners map[net.Listener]struct{} activeConn map[*conn]struct{} doneChan chan struct{} onShutdown []func() }
在初始化server的时候主要用到了Addr和Handler。Handler是一个接口:
//处理程序对HTTP请求的响应 type Handler interface { ServeHTTP(ResponseWriter, *Request) }

浙公网安备 33010602011771号