Golang HTTP服务:构建高效Web应用的基石

发表时间: 2024-06-08 12:17

服务端

http_server/main.go

package mainimport (    "log"    "net/http"    "time")var (    Addr = ":1210")func main() {    // 创建路由器    mux := http.NewServeMux()    // 设置路由规则    mux.HandleFunc("/index", sayBye)    // 创建服务器    server := &http.Server{        Addr: Addr,        WriteTimeout: time.Second * 3,        Handler: mux,		}    // 监听端口并提供服务    log.Println("Starting httpserver at "+Addr)    log.Fatal(server.ListenAndServe())    }    func sayBye(w http.ResponseWriter, r *http.Request) {    time.Sleep(1 * time.Second)    w.Write([]byte("bye bye ,this is httpServer"))}

客户端

http_client/main.go

package mainimport (    "fmt"    "io/ioutil"    "net"    "net/http"    "time")func main() {    // 创建连接池    transport := &http.Transport{        DialContext: (&net.Dialer{        Timeout: 30 * time.Second, //连接超时        KeepAlive: 30 * time.Second, //探活时间        }).DialContext,        MaxIdleConns: 100, //最大空闲连接        IdleConnTimeout: 90 * time.Second, //空闲超时时间        TLSHandshakeTimeout: 10 * time.Second, //tls握手超时时间        ExpectContinueTimeout: 1 * time.Second, //100-continue状态码超时时间    }    // 创建客户端    client := &http.Client{        Timeout: time.Second * 30, //请求超时时间        Transport: transport,    }    // 请求数据    resp, err := client.Get("http://127.0.0.1:1210/index")    if err != nil {        panic(err)    }    defer resp.Body.Close()    // 读取内容    bds, err := ioutil.ReadAll(resp.Body)    if err != nil {        panic(err)    }    fmt.Println(string(bds))}

客户端浏览器访问:

> # curl -v 'http://127.0.0.1:1210/index'