Go网络编程之http编程

ByWhat'sUs

Go网络编程之http编程

http的服务端简单案例

server.go

package main

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

func main() {
    http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
        params := request.URL.Query();
        fmt.Fprintf(writer, "你好, %s", params.Get("name"))
    })
    err := http.ListenAndServeTLS(":443", "./ca.crt", "./ca.key",nil)
    if err != nil {
        log.Fatalf("启动 HTTPS 服务器失败: %v", err)
    }
}

http客户端简单案例

client.go

package main

import (
    "crypto/tls"
    "fmt"
    "io"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "https://127.0.0.1:443/hello?name=http", nil)
    if err != nil {
        fmt.Printf("请求初始化失败:%v", err)
        return
    }

    // 设置跳过不安全的 HTTPS
    tls11Transport := &http.Transport{
        MaxIdleConnsPerHost: 10,
        TLSClientConfig: &tls.Config{
            MaxVersion: tls.VersionTLS11,
            InsecureSkipVerify: true,
        },
    }

    client := &http.Client{
        Transport: tls11Transport,
    }

    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("客户端发起请求失败:%v", err)
        return
    }

    defer resp.Body.Close()
    io.Copy(os.Stdout, resp.Body)
}

About the author

What'sUs administrator

Leave a Reply

PHP Code Snippets Powered By : XYZScripts.com