How to add Image in HTML file in Go

huangapple go评论85阅读模式
英文:

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:

&lt;body&gt;
    &lt;table&gt;
        &lt;tr&gt;
            &lt;td&gt;Jill&lt;/td&gt;
            &lt;td&gt;Smith&lt;/td&gt;
            &lt;td&gt;&lt;img src=&quot;test.jpg&quot; border=3 height=100 width=300 /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;Eve&lt;/td&gt;
            &lt;td&gt;Jackson&lt;/td&gt;
            &lt;td&gt;94&lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
&lt;/body&gt;

Below is the Go language Code for this :-

// * /
func rootHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == &quot;/&quot; {
        homeHandler(w, r)
    } else {
        log.Printf(&quot;rootHandler: Could not forward request for %s any further.&quot;, 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 (
	&quot;fmt&quot;
	&quot;net/http&quot;
)

func RootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, &quot;&lt;h1&gt;Hello&lt;/h1&gt;&lt;img src=&#39;/img/MR.png&#39;/&gt;&quot;)
}

func main() {
	http.HandleFunc(&quot;/&quot;, RootHandler) // homepage

	http.HandleFunc(&quot;/img/&quot;, func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})

	http.ListenAndServe(&quot;:8080&quot;, nil)
}

huangapple
  • 本文由 发表于 2015年12月24日 19:30:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/34452128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定