英文:
How to add Image in HTML file in Go
问题
首先,我使用Notepad ++创建了一个HTML文件,其中包含以下代码:
<body>
    <table>
        <tr>
            <td>Jill</td>
            <td>Smith</td>
            <td><img src="test.jpg" border=3 height=100 width=300 /></td>
        </tr>
        <tr>
            <td>Eve</td>
            <td>Jackson</td>
            <td>94</td>
        </tr>
    </table>
</body>
以下是用于此目的的Go语言代码:
// * /
func rootHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/" {
        homeHandler(w, r)
    } else {
        log.Printf("rootHandler: Could not forward request for %s any further.", r.RequestURI)
        errNotFound(w, r)
    }
}
我希望在浏览器中加载test.png,但它没有起作用。
英文:
First of all, I created an HTML file using Notepad ++ with this code:
<body>
    <table>
        <tr>
            <td>Jill</td>
            <td>Smith</td>
            <td><img src="test.jpg" border=3 height=100 width=300 /></td>
        </tr>
        <tr>
            <td>Eve</td>
            <td>Jackson</td>
            <td>94</td>
        </tr>
    </table>
</body>
Below is the Go language Code for this :-
// * /
func rootHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/" {
        homeHandler(w, r)
    } else {
        log.Printf("rootHandler: Could not forward request for %s any further.", r.RequestURI)
        errNotFound(w, r)
    }
}
I want test.png should be loaded in browser but its not working.
答案1
得分: 1
你可以为处理位于img目录中的函数添加一个处理程序,例如。
以下是一种可能的实现方式:
package main
import (
	"fmt"
	"net/http"
)
func RootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<h1>Hello</h1><img src='/img/MR.png'/>")
}
func main() {
	http.HandleFunc("/", RootHandler) // 主页
	http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})
	http.ListenAndServe(":8080", nil)
}
英文:
You can add an handler for dealing with function in an img directory, for example.
Here is one possible way to do it:
package main
import (
	"fmt"
	"net/http"
)
func RootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<h1>Hello</h1><img src='/img/MR.png'/>")
}
func main() {
	http.HandleFunc("/", RootHandler) // homepage
	http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})
	http.ListenAndServe(":8080", nil)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论