2014-01-15 42 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的内容。

如果它不起作用,也许增加的错误处理可能会有所帮助。代码是正确的。

相关问题