登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-03 19:45:23 299浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《如何将正文标题添加到 Fprintf 输出?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我正在尝试将 go 添加到我的代码示例中:

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, "go").它可以工作,但会弄乱旁边的字符串。我不想仅使用 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, "")
    fmt.Fprintf(w, "")
    fmt.Fprintf(w, "%s", "Go")
    fmt.Fprintf(w, "")
    fmt.Fprintf(w, "")
    fmt.Fprintf(w, "

System info: Hostname [pod name]: %s", hostname) fmt.Fprintf(w, "

Current URL: %s", r.Host) fmt.Fprintf(w, "") fmt.Fprintf(w, "") } func main() { http.HandleFunc("/favicon.ico", favicon) http.HandleFunc("/", sayhelloName) log.Fatal(http.ListenAndServe(":8080", nil)) }

本篇关于《如何将正文标题添加到 Fprintf 输出?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>