How to set Home page and static files in same path

huangapple go评论76阅读模式
英文:

How to set Home page and static files in same path

问题

如果我运行URL http://localhost:8080/,我想要运行Index函数。如果我运行http://localhost:8080/robot.txt,它应该显示static文件夹中的文件。

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

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Index")
}

如何实现这个功能?

目前,我遇到了以下错误:

panic: http: multiple registrations for /

这是我的目录结构:

main.go
static\
  | robot.txt
  | favicon.ico
  | sitemap.xml
英文:

if I run the URL http://localhost:8080/ I want to run the Index function and If I run http://localhost:8080/robot.txt it should show static folder files

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

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Index")
}

How to do this.

Currently, I'm getting this error

> panic: http: multiple registrations for /

This is my directory structure

main.go
static\
  | robot.txt
  | favicon.ico
  | sitemap.xml

答案1

得分: 2

将索引处理程序委托给文件服务器:

func main() {
    http.HandleFunc("/", Index)
    http.ListenAndServe(":8080", nil)
}

var fserve = http.StripPrefix("/", http.FileServer(http.Dir("static"))))

func Index(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        fserve.ServeHTTP(w, r)
        return
    }
    fmt.Fprintln(w, "Index")
}

将上述代码翻译为中文如下:

func main() {
    http.HandleFunc("/", Index)
    http.ListenAndServe(":8080", nil)
}

var fserve = http.StripPrefix("/", http.FileServer(http.Dir("static"))))

func Index(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        fserve.ServeHTTP(w, r)
        return
    }
    fmt.Fprintln(w, "Index")
}
英文:

Delegate to the file server from the index handler:

func main() {
    http.HandleFunc("/", Index)
    http.ListenAndServe(":8080", nil)
}

var fserve = http.StripPrefix("/", http.FileServer(http.Dir("static"))))

func Index(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != “/“ {
        fserve.ServeHTTP(w, r)
        return
    }
    fmt.Fprintln(w, "Index")
}

huangapple
  • 本文由 发表于 2021年12月19日 04:04:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/70406720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定