2014-01-15 43 views
1
import (
    "net/http" 
) 

func main() { 
    http.Handle("/", http.FileServer(http.Dir("static"))) 
    http.ListenAndServe(":8080", nil) 
} 

我導航到本地主機:8080 /並得到404錯誤。我究竟做錯了什麼?含main.go404當試圖從文件系統提供文件

main.go 
static 
    |- index.html 

而且:

+0

您希望從GET /?中得到什麼? – Volker

+0

我的Index.html在靜態文件夾中 – Dante

+0

'server.RegisterHandlers()'做了什麼?假如你有一個名爲「static」的文件夾,沒有它,代碼應該可以正常工作。 – ANisus

回答

2

試試這個:

import (
    "net/http" 
    "os" 
) 

func main() { 
    server.RegisterHandlers() 

    // Get the running directory. 
    runningDirectory, err := os.Getwd() 
    if err != nil { 
     // Handle the error. 
     return err 
    } 

    http.Handle("/", http.FileServer(http.Dir(runningDirectory + "/static")) 
    http.ListenAndServe(":8080", nil) 
} 
+0

不錯,它的工作!你知道爲什麼通常一個親戚應該足夠的時候可能需要一條完整路徑嗎? – ANisus

0

結構如下

package main 

import (
    "net/http" 
) 

func main() { 
    http.Handle("/", http.FileServer(http.Dir("static"))) 
    if err := http.ListenAndServe(":8080", nil); err != nil { 
     panic(err) 
    } 
} 

go run main.go運行您的解決方案後,你應該能夠去localhost:8080/,最後得到0123的內容。

如果它不起作用,也許增加的錯誤處理可能會有所幫助。代碼是正確的。

相關問題