go http服务

语言:
Go
16 浏览
0 收藏
2小时前

代码实现

Go
package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<h1>Hello, World!<h1>")
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.ListenAndServe(":80", nil)
}

本示例提供一个最基础的Go语言HTTP服务代码片段。在Go语言中,net/http包提供了构建HTTP服务器所需的所有工具。HTTP服务器是一种能够接收HTTP请求并返回HTTP响应的软件。它通常运行在Web服务器上,处理来自客户端的请求,并根据请求的内容返回相应的资源或数据。

#HTTP

片段说明

代码解析

  • 导入包:我们导入了fmtnet/http包。fmt用于格式化输出,net/http用于处理HTTP请求和响应。
  • 定义处理函数:helloHandler是一个处理函数,它接收两个参数:http.ResponseWriter和*http.Requesthttp.ResponseWriter用于向客户端发送响应,*http.Request包含了客户端请求的所有信息。
  • 注册路由:http.HandleFunc("/", helloHandler)将根路径"/"helloHandler函数绑定。当客户端访问根路径时,服务器将调用helloHandler函数来处理请求。
  • 启动http服务器:http.ListenAndServe(":80", nil)启动服务器并监听80端口。nil表示使用默认的多路复用器(DefaultServeMux)。

运行

将上述代码保存为main.go,在终端中运行一下命令:

go run main.go

打开浏览器并访问http://localhost:80 ,将会在页面上显示“Hello,World”。

评论

加载中...