http - 如何使用 golang 定义自定义 mux

标签 http go

我查看了 mux 的源代码,但我只想要一些简单的东西,而不是使用所有功能。

我想在 url 中获取 “id” 的值,如/url/{id},在 req.Form 中设置值并像 mux 一样清理路径。

像这样的代码

    r:=http.NewServeMux()
    r.HandlerFunc("/",func(w http.ResponseWriter,r *http.Request){
        // Clean path to canonical form and redirect.
        if p := cleanPath(req.URL.Path); p != req.URL.Path {
            url := *req.URL
            url.Path = p
            p = url.String()
            //根据HTTP的协议重定向
            w.Header().Set("Location", p)
            w.WriteHeader(http.StatusMovedPermanently)
            return
        }
                // some code check the url parse id and set to req.form
    })
            //then add some specific url handlers.

在 go doc 中,它说长模式将比短模式具有更高的优先级。 我想在所有处理程序之前运行一些东西(解析 ID、清理路径等)。

我不想放弃 defaultmux 的功能。我应该重新定义一条全新的路线,还是使用 http.NewServeMux()?如果我使用 http.NewServerMux(),我应该如何在保持特性的同时添加一些东西?

最佳答案

我们使用了http://www.gorillatoolkit.org/pkg/mux在我们的生产堆栈中工作了一年多,对此非常满意。

对于我托管的一些非常简单的网站,我使用像这样的内置路由:

package main

import (
  "flag"
  "fmt"
  "net/http"
  "os"
)

const (
  version = "0.1.0"
)

var (
  port   uint
)

func init() {
  flag.UintVar(&port, "port", 8000, "the port to listen on")
  flag.UintVar(&port, "p", 8000, "the port to listen on")
}

func main() {
  flag.Parse()

  // Retrieve the current working directory.
  path, err := os.Getwd()
  if err != nil {
    panic(err)
  }
  http.HandleFunc("/gallery/view.aspx", handleGallery)
  http.HandleFunc("/gallery/viewLarge.aspx", handleViewLarge)
  http.HandleFunc("/ir.ashx", handleImageResize)
  http.Handle("/", http.FileServer(http.Dir(path)))

  panic(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}

让我知道您想要的路线是什么,我可以给您一个更具体的例子来说明您正在寻找什么。

关于http - 如何使用 golang 定义自定义 mux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978883/

相关文章:

http - 如何强制网络浏览器缓存图像

java - 如何在java中进行批量http调用

python - golang和python zlib的区别

go - 正确读取用户的输入

ios - 通过http上传视频

html - 是否存在省略 http ://or https://will fail to work in certain browsers? 中的协议(protocol)的情况

http - 在 Azure VM 上使用鱿鱼代理绕过 Internet 过滤器的问题

git - 去包装: How to avoid 'cannot find package' error when submitting PRs from fork?

go - golang 上的公历包

go - 传入请求:具有自定义类型字段的上下文