首页 > 解决方案 > 文件服务器返回 404

问题描述

我真正想做的是提供两个目录作为文件服务器,/assets/web/public. 作为参考,这是我的项目结构:

/root
    /assets
    /web
        /public
        /src
        /templates
    main.go

但是,当我运行服务器时,/public路由返回 404,而资产很好。我梳理了参考资料和一堆教程,我所做的一切都应该在董事会之上。

package main

import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "os"
    "path/filepath"

    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    // here is where i set up the file servers
    publicHandler := http.FileServer(http.Dir(filepath.Join("web", "public")))
    r.PathPrefix("/pubic/").Handler(http.StripPrefix("/pubic/", publicHandler))

    assetHandler := http.FileServer(http.Dir("assets"))
    r.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", assetHandler))

    r.HandleFunc("/", s.HandleHome())
    
    port := fmt.Sprintf(":%d", 5123)
    http.ListenAndServe(port, r)
}

func (s *Server) HandleHome() http.HandlerFunc {
    tpl, err := template.New("").ParseFiles("web/templates/index.tpl")
    if err != nil {
        panic(err)
    }

    return func(w http.ResponseWriter, r *http.Request) {
        err = tpl.ExecuteTemplate(w, "index", nil)
        if err != nil {
            http.Error(w, "oops", http.StatusInternalServerError)
        }
    }
}

标签: gogorillafileserver

解决方案


推荐阅读