2017-07-24 49 views
0

我有一個簡單的網絡服務器,我想在瀏覽器中打開圖像。問題是瀏覽器無法打開我發送的圖像。如何在網絡服務器中打開圖像

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項目

回答

2

這是因爲你一個處理任何圖片的請求任何專用路線。

我的建議是根據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) 
} 
+0

謝謝你的幫助。有用! –