以下是一个简单的示例,展示如何在 Go 中返回 HTML:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    html := "<html><head><title>Hello World</title></head><body><h1>Hello World!</h1></body></html>"
    fmt.Fprint(w, html)
}

在这个示例中,我们定义了一个 handler 函数,它会向客户端返回一个包含 "Hello World!" 的 HTML 页面。我们使用 fmt.Fprint 函数将 HTML 写入响应中,然后将响应返回给客户端。

我们将该 handler 函数绑定到根路径上,这意味着当客户端请求网站的根路径时,该函数将被调用。我们使用 http.HandleFunc 函数来完成此操作。

最后,我们调用 http.ListenAndServe 函数来启动 Web 服务器,并监听 8080 端口上的请求

golang 返回html

原文地址: http://www.cveoy.top/t/topic/eaZH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录