2013-05-21 66 views
12

我想寫一個簡單的網絡服務器,去做以下事情:當我去http://example.go:8080/image,它返回一個靜態圖像。 我正在關注一個例子,我發現here。在這個例子中,他們實現這個方法:go-lang簡單的網絡服務器:服務靜態圖像

func handler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) 
} 

,然後參考這裏:

... 
... 
http.HandleFunc("/", handler) 

現在,我要做的是服務,而不是寫入字符串的圖像。 我該怎麼辦?

回答

21

您可以使用http.FileServer函數來提供靜態文件。

package main 

import (
    "log" 
    "net/http" 
) 

func main() { 
    http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("path/to/file")))) 
    if err := http.ListenAndServe(":8080", nil); err != nil { 
     log.Fatal("ListenAndServe: ", err) 
    } 
} 

編輯:更多idiomatic的代碼。

EDIT 2:該代碼時的瀏覽器請求http://example.go/image.png

http.StripPrefix函數這裏是在這種情況下嚴格不必要的,因爲所處理的路徑是Web根以上將返回一個圖像image.png。如果圖像要從路徑http://example.go/images/image.png提供,那麼上面的行將需要爲http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("path/to/file"))))

​​

+0

非常感謝!你可以添加一些關於StripPrefix和FileServer在這個上下文中的含義和用法的單詞嗎? – levtatarov

+1

在這種情況下,StripPrefix並不是真正必要的,因爲您從Web服務器的根目錄提供服務。當你想從不同的路徑服務器時,它確實是必需的。看看http://golang.org/pkg/net/http/#StripPrefix和http://golang.org/pkg/net/http/#FileServer。 – Intermernet