gpt4 book ai didi

go - 如何将正文标题添加到 Fprintf 输出?

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:38 30 4
gpt4 key购买 nike

我正在尝试添加 <title>Go</title>到我的代码示例:

package main

import (
"fmt"
"net/http"
"os"
)

func favicon(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "favicon.ico")
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
hostname, _ := os.Hostname()
fmt.Fprintf(w, "\n\nSystem info:\nHostname [pod name]: %s", hostname)
fmt.Fprintf(w, "\nCurrent URL: %s\n", r.Host)
}

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

我尝试添加如下内容: fmt.Fprintf(w, "<title>Go</title>") .它可以工作,但会弄乱旁边的字符串。我不想只使用 html 模板向页面添加标题。有没有办法在一个字符串中添加标题?

最佳答案

未使用 html 模板。只使用了 fmt.Fprintf。

package main

import (
"fmt"
"log"
"net/http"
"os"
)

func favicon(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "favicon.ico")
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
hostname, _ := os.Hostname()

fmt.Fprintf(w, "<html>")
fmt.Fprintf(w, "<head>")
fmt.Fprintf(w, "<title>%s</title>", "Go")
fmt.Fprintf(w, "</head>")
fmt.Fprintf(w, "<body>")
fmt.Fprintf(w, "<h1>System info: Hostname [pod name]: %s", hostname)
fmt.Fprintf(w, "<h1>Current URL: %s", r.Host)
fmt.Fprintf(w, "</body>")
fmt.Fprintf(w, "</html>")
}

func main() {
http.HandleFunc("/favicon.ico", favicon)
http.HandleFunc("/", sayhelloName)

log.Fatal(http.ListenAndServe(":8080", nil))
}

关于go - 如何将正文标题添加到 Fprintf 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167541/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com