建网站图片怎么找,金隅嘉华大厦网站建设公司,网站规划和建设进度,海南省建设公司官网#x1f308;Don’t worry , just coding! 内耗与overthinking只会削弱你的精力#xff0c;虚度你的光阴#xff0c;每天迈出一小步#xff0c;回头时发现已经走了很远。
#x1f4d7;概念 在 Go 语言中#xff0c;net/http 包提供了强大的 HTTP 客户端和服务器功能。 Don’t worry , just coding! 内耗与overthinking只会削弱你的精力虚度你的光阴每天迈出一小步回头时发现已经走了很远。
概念 在 Go 语言中net/http 包提供了强大的 HTTP 客户端和服务器功能。 代码
HTTP 客户端
package mainimport (//bufio用于缓冲 I/O 操作提供了扫描输入的功能。//fmt用于格式化输入输出。//net/http提供 HTTP 客户端和服务器的功能。bufiofmtnet/http
)func main() {//使用 http.Get 方法发送 GET 请求到指定的 URL//返回一个 HTTP 响应和一个错误对象。resp, err : http.Get(https://www.baidu.com)if err ! nil {panic(err)}//使用 defer 关键字确保在 main 函数结束时关闭响应体释放资源。defer resp.Body.Close()//打印响应的状态码resp.Statusfmt.Println(Response status:, resp.Status)//创建一个新的扫描器用于逐行读取响应体的内容。scanner : bufio.NewScanner(resp.Body)//使用循环读取响应的前五行内容。scanner.Scan() 方法返回 true 表示还有更多的内容可供读取scanner.Text() 返回当前行的文本。for i : 0; scanner.Scan() i 5; i {fmt.Println(scanner.Text())}//检查扫描过程中是否发生错误。如果有错误终止程序并输出错误信息。if err : scanner.Err(); err ! nil {panic(err)}
}HTTP 服务端
package mainimport (fmt//net/http提供 HTTP 客户端和服务器的功能。net/http
)// 定义了一个名为 hello 的处理函数它接受两个参数
// w http.ResponseWriter用于构建 HTTP 响应。
// req *http.Request包含了 HTTP 请求的信息。
func hello(w http.ResponseWriter, req *http.Request) {//使用 fmt.Fprintf 向响应写入字符串 hello。fmt.Fprintf(w, hello\n)
}// 定义了一个名为 headers 的处理函数功能是输出请求的所有 HTTP 头
func headers(w http.ResponseWriter, req *http.Request) {//使用 req.Header 获取请求头的键值对。for name, headers : range req.Header {//遍历每个头的名称和对应的值并将其写入响应中。for _, h : range headers {fmt.Fprintf(w, %v: %v\n, name, h)}}
}func main() {//在 main 函数中使用 http.HandleFunc 注册了两个路由///hello 路由会调用 hello 函数。///headers 路由会调用 headers 函数。http.HandleFunc(/hello, hello)http.HandleFunc(/headers, headers)//启动 HTTP 服务器监听在端口 8090。nil 表示使用默认的多路复用器。http.ListenAndServe(:8090, nil)
}路由和多路复用
mux : http.NewServeMux()
mux.HandleFunc(/hello, helloHandler)
mux.HandleFunc(/goodbye, goodbyeHandler)
http.ListenAndServe(:8080, mux)中间件
func loggingMiddleware(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Println(Request received:, r.Method, r.URL)next.ServeHTTP(w, r)})
}JSON处理
package mainimport (encoding/jsonnet/http
)type Message struct {Text string json:text
}func jsonHandler(w http.ResponseWriter, r *http.Request) {msg : Message{Text: Hello, JSON!}w.Header().Set(Content-Type, application/json)json.NewEncoder(w).Encode(msg)
}
理解
使用 http.ListenAndServe 启动服务器。使用 http.Get、http.Post 等函数可以轻松发送 HTTP 请求。http.Request 对象包含了请求的信息例如请求方法、URL、头信息等。http.ResponseWriter 用于构建和发送 HTTP 响应。
无人扶我青云志我自踏雪至山巅。