【问题标题】:How to serve a lot of pages [closed]如何提供大量页面[关闭]
【发布时间】:2020-02-16 01:36:25
【问题描述】:

我想创建一个包含许多子页面的 Web 服务器。例如

www.mainpage.com - 主页,我有很多子页面

www.mainpage.com/1page; www.mainpage.com/2page; www.mainpage.com/3page; ..... www.mainpage.com/999page

我不知道如何处理所有这些页面。我认为这种方式是不正确的

func main() {
    http.HandleFunc("/1page", PageHandler)
    http.HandleFunc("/2page", PageHandler)
    ......
    http.HandleFunc("/999page", PageHandler)

    fmt.Println("Server is listening...")
    http.ListenAndServe(":8181", nil)
}

【问题讨论】:

    标签: go


    【解决方案1】:

    http.HandleFunc 的文档说:

    ServeMux 的文档解释了模式是如何匹配的。

    ServeMux 说:

    请注意,由于以斜杠结尾的模式命名了根子树,因此模式“/”匹配其他注册模式不匹配的所有路径,而不仅仅是路径 ==“/”的 URL。

    传递给处理函数的Request对象包含请求URL

    所以只需在根目录注册一个模式:

        http.HandleFunc("/", PageHandler)
    

    【讨论】:

    • 谢谢!如果我有很多 subsub.... 页面,比如 mainpage/1page/2page/3page....
    • “匹配所有路径” -- 没关系。
    【解决方案2】:

    您是否尝试过提供静态文件?

    检查这个答案:How do you serve a static html file using a go web server?

    package main
    
    import (
            "net/http"
    )
    
    func main() {
            http.Handle("/", http.FileServer(http.Dir("./static")))
            http.ListenAndServe(":3000", nil)
    }
    

    如果您不想使用静态文件而只使用http.Handler,您可以使用循环来注册您的处理函数。例如:

    package main
    
    import (
        "fmt"
        "net/http"
        "strconv"
    )
    
    func main() {
        for i := 1; i < 1000; i++ {
            http.HandleFunc(fmt.Sprintf("/%dpage", i), PageHandler(i))
        }
        fmt.Println("Server is listening...")
        http.ListenAndServe(":8181", nil)
    }
    
    func PageHandler(i int) func(http.ResponseWriter, *http.Request) {
        return func(resp http.ResponseWriter, req *http.Request) {
            resp.WriteHeader(200)
            resp.Write([]byte(strconv.Itoa(i)))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2020-11-14
      • 2016-08-24
      • 2020-11-12
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多