在 Golang 中,可以使用 net/http 包来定义和使用服务。以下是一个简单的示例:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", nil)
}
在这个例子中,我们首先定义了一个名为 helloHandler 的函数,它接收一个 ResponseWriter 和一个 Request 参数,并将字符串 “Hello, World!” 写入到 ResponseWriter 中。
然后,在 main 函数中,我们使用 http.HandleFunc 函数将 /hello 路径映射到我们刚才定义的 helloHandler 函数。最后,我们使用 http.ListenAndServe 启动服务并监听端口 8080。
要运行此程序,请执行以下命令:
$ go run main.go
现在,您可以在浏览器中打开 http://localhost:8080/hello 来查看输出结果。
当然,这只是一个非常基本的示例。如果您需要更复杂的功能(例如处理 HTTPS 请求、处理路由、提供静态文件等),则需要深入学习 net/http 包。




