【问题标题】:How to open images in webserver如何在网络服务器中打开图像
【发布时间】:2017-12-29 15:13:20
【问题描述】:

我有一个简单的网络服务器,我想在浏览器中打开图像。问题是浏览器无法打开我发送的图像。

package main

import (

  "io/ioutil"
  "net/http"
  "io"
  "html/template"
  "fmt"

 )  
func main() {



http.HandleFunc("/images", images)


http.ListenAndServe(":8080", nil)
}
func images(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("templates/link.html")
if err != nil {
    fmt.Fprintf(w, err.Error())
    return
}

t.ExecuteTemplate(w, "link", nil)
}

还有我的 html 模板包,我在其中创建了一个指向计算机上文件的链接。称为link.html

  {{ define "link" }}


  <!DOCTYPE html>
  <html lang="en">
   <head>
   <meta charset="UTF-8">
   <title>Title</title>
   </head>
   <body>

   <p> <a href="/images/2.jpg">apple</a></p>
   <br>

   </body>
   </html>


   {{ end }}

我不明白为什么它不起作用。会很高兴得到帮助。此外,我想添加到服务器的所有文件都在这个 golang 项目中

【问题讨论】:

    标签: go


    【解决方案1】:

    这是因为您没有任何专用路由来处理任何图像的请求。

    我的建议是初始化一个基于 URI 路径名提供文件的 HTTP 处理程序。您可以使用该处理程序作为提供图像的一种方式。

    fs := http.FileServer(http.Dir("images"))
    

    然后绑定它:

    http.Handle("/images/", http.StripPrefix("/images/", fs))
    

    这是您的完整代码以及我的建议:

    package main
    
    import (
      "fmt"
      "html/template"
      "net/http"
    )
    
    func main() {
      // We're creating a file handler, here.
      fs := http.FileServer(http.Dir("images"))
    
      http.HandleFunc("/images", images)
    
      // We're binding the handler to the `/images` route, here.
      http.Handle("/images/", http.StripPrefix("/images/", fs))
    
      http.ListenAndServe(":8080", nil)
    }
    
    func images(w http.ResponseWriter, r *http.Request) {
      t, err := template.ParseFiles("templates/link.html")
      if err != nil {
        fmt.Fprintf(w, err.Error())
        return
      }
    
      t.ExecuteTemplate(w, "link", nil)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-23
      • 2011-02-14
      • 2018-07-14
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 2016-01-16
      • 2015-12-14
      相关资源
      最近更新 更多