当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


GO ListenAndServe用法及代码示例

GO语言"net/http"包中"ListenAndServe"函数的用法及代码示例。

用法:

func ListenAndServe(addr string, handler Handler) error

ListenAndServe 侦听 TCP 网络地址 addr,然后使用处理程序调用 Serve 以处理传入连接上的请求。接受的连接配置为启用 TCP keep-alives。

处理程序通常为零,在这种情况下使用DefaultServeMux。

ListenAndServe 始终返回非零错误。

例子:

package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    // Hello world, the web server

    helloHandler := func(w http.ResponseWriter, req *http.Request) {
        io.WriteString(w, "Hello, world!\n")
    }

    http.HandleFunc("/hello", helloHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 ListenAndServe。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。