在 mux 处理调用之前预污染索引页

问题描述 投票:0回答:1

我最近出于测试目的构建了一个小型博客网站,在用 Go 编写服务器时我遇到了这个问题。我将网站的所有文件都放在

static
文件夹中,该文件夹也是
http.FileServer
赋予
mux.Handle
的根。一切正常,除了我需要用文章的数据预先污染索引页的数据。

如果我用

mux.HandleFunc
构建索引页面并以这种方式调用索引,我会丢失所有 CSS 格式,因为 mux 当然不知道在哪里可以找到它,因为他没有根
fs
可以检查。

所以我的问题基本上是:是否可以用一些数据预先填充索引页(例如,从 json 文件中读取数据并使用

template.ParseFiles
解析它)并仍然使用
mux.Handle
作为挂载点网站?

package main

import (
    "mywebsite/handlers"
    "net/http"
)

func main() {

    var mux = http.NewServeMux()
    mux.Handle("/", http.FileServer(http.Dir("static")))

    /*This throws panic: pattern "/" (registered at /home/nicola/Desktop/mywebsite/main.go:12) conflicts with pattern "/" (registered at /home/nicola/Desktop/mywebsite/main.go:11):
    / matches the same requests as / */
    mux.HandleFunc("/", handlers.IndexHandler)

    err := http.ListenAndServe(":3345", mux)
    if err != nil {
        panic(err)
    }
}

非常感谢您的任何提示!

go gorilla go-http
1个回答
0
投票

我以某种方式解决了这样的问题。将 css 移至名为

css
的单独目录中。 所以基本上我的工作空间现在是这样的:

.
├── blogposts
│   ├── 1.html
│   └── 2.html
├── go.mod
├── handlers
│   ├── contactshandler.go
│   ├── indexhandler.go
│   ├── projectshandler.go
│   └── readerhandler.go
├── main.go
└── static
    ├── components
    │   ├── navigation-links1.css
    │   └── navigation-links1.html
    ├── contacts.html
    ├── css
    │   ├── 404.css
    │   ├── contacts.css
    │   ├── index.css
    │   ├── projects.css
    │   └── style.css
    ├── index.html
    ├── package.json
    ├── projects.html
    └── public
        └── external
            ├── 1f3eb.svg
            └── 1f44b.svg

然后像这样路由多路复用器

    mux.Handle("/css/", http.FileServer(http.Dir("static")))
    mux.Handle("/components/", http.FileServer(http.Dir("static")))
    mux.Handle("/public/external/", http.FileServer(http.Dir("static")))
    
    mux.HandleFunc("/", handlers.IndexHandler)
    mux.HandleFunc("/projects", handlers.ProjectsHandler)
    mux.HandleFunc("/contacts", handlers.ContactsHandler)
    mux.HandleFunc("/read/", handlers.ReaderHandler)

所以基本上

mux
现在可以处理三个不同的
fs
,一个用于
static
内的每个文件夹,提供 CSS 和其他图形内容。 这不是最漂亮的工作,但对于这个小网站来说它工作得很好!

© www.soinside.com 2019 - 2024. All rights reserved.