package main
import (
"fmt"
"log"
"net/http"
)
func HelloServer(w http.ResponseWriter, req *http.Request) {
fmt.Println("Inside HelloServer handler")
// fmt.Fprint() 和 fmt.Fprintf() 都是可以用来写入 http.ResponseWriter 的函数(他们实现了 io.Writer)。
fmt.Fprintf(w, "Hello,"+req.URL.Path[1:])
}
// 运行起来之后,打开浏览器并输入 url 地址:http://localhost:8080/world,浏览器就会出现文字:Hello, world,网页服务器会响应你在 :8080/ 后边输入的内容。
func main() {
// http.HandleFunc 注册了一个处理函数(这里是 HelloServer())来处理对应 / 的请求。
// http.HandleFunc中的两个参数 第一个参数是请求的路径,第二个参数是当路径被请求时,需要调用的处理函数的引用
// 除了 http.HandleFunc("/", Hfunc),其中的 HFunc 是一个处理函数,签名为:func HFunc(w http.ResponseWriter, req *http.Request)
// 也可以使用这种方式:http.Handle("/", http.HandlerFunc(HFunc))
// HandlerFunc 只是定义了上述 HFunc 签名的别名:
// type HandlerFunc func(ResponseWriter, *Request)
// http.Handle("/", http.HandlerFunc(HelloServer))
http.HandleFunc("/", HelloServer)
// 使用 http.ListenAndServe("localhost:8080", nil) 函数,如果成功会返回空,否则会返回一个错误(地址 localhost 部分可以省略,8080 是指定的端口号)。
// 如果你需要使用安全的 https 连接,使用 http.ListenAndServeTLS() 代替 http.ListenAndServe()
// 可以替换成以下写法
// http.ListenAndServe(":8080", http.HandlerFunc(HelloServer))
err := http.ListenAndServe("localhost:8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
golang 实现http请求调用
于 2024-03-04 16:31:16 首次发布