gpt4 book ai didi

html - 如何将图像插入 HTML Golang 文件?

转载 作者:IT王子 更新时间:2023-10-29 02:21:31 26 4
gpt4 key购买 nike

package main

import (
"fmt"
"net/http"
)

func index_handler(w http.ResponseWriter, r *http.Request) {
// MAIN SECTION HTML CODE
fmt.Fprintf(w, "<h1>Whoa, Go is neat!</h1>")
fmt.Fprintf(w, "<title>Go</title>")
fmt.Fprintf(w, "<img src='gopher.jpeg' alt='gopher' style='width:235px;height:320px;'>")
}

func about_handler(w http.ResponseWriter, r *http.Request) {
// ABOUT SECTION HTML CODE
fmt.Fprintf(w, "<title>Go/about/</title>")
fmt.Fprintf(w, "Expert web design by -")
}

func main() {
http.HandleFunc("/", index_handler)
http.HandleFunc("/about/", about_handler)
http.ListenAndServe(":8000", nil)
}

在我的代码中,我尝试将图像放在屏幕上。所有这一切都是使用 alt。我的 jpeg 文件与我的代码位于同一目录中。自从我使用 Go 以来,有什么我必须添加的吗?感谢您的帮助。

最佳答案

首先,我建议您将图像、css、js 和其他资源放在一个单独的文件夹中,而不是放在您的 go 应用程序所在的文件夹中,子文件夹也可以,只需将它们与您的 go 代码分开即可。

完成后,您需要告诉 Go 如何以及从何处提供这些文件。

这是一个例子:

package main

import (
"fmt"
"net/http"
)

func index_handler(w http.ResponseWriter, r *http.Request) {
// MAIN SECTION HTML CODE
fmt.Fprintf(w, "<h1>Whoa, Go is neat!</h1>")
fmt.Fprintf(w, "<title>Go</title>")
fmt.Fprintf(w, "<img src='assets/gopher.jpeg' alt='gopher' style='width:235px;height:320px;'>")
}

func about_handler(w http.ResponseWriter, r *http.Request) {
// ABOUT SECTION HTML CODE
fmt.Fprintf(w, "<title>Go/about/</title>")
fmt.Fprintf(w, "Expert web design by JT Skrivanek")
}

func main() {
http.HandleFunc("/", index_handler)
http.HandleFunc("/about/", about_handler)
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets"))))
http.ListenAndServe(":8000", nil)
}

这是假设您的项目结构如下所示:

└── app
├── assets
│   └── gopher.jpeg
└── main.go

并且您已经从 app 内部启动了您的应用程序文件夹。

另请注意,您还必须更改 HTML 图像链接以反射(reflect)更改。例如。;而不是 <img src='gopher.jpeg' ...你有<img src='assets/gopher.jpeg' ...

关于html - 如何将图像插入 HTML Golang 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47115482/

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