how to define custom mux with golang

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

how to define custom mux with golang

问题

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

我想要从URL中获取"id"的值,就像"/url/{id}"这样的路径,将该值设置在req.Form中,并像mux一样清理路径。

代码如下:

r := http.NewServeMux()
r.HandlerFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // 清理路径并重定向到规范形式。
    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
    }
    // 一些代码检查URL解析的id并设置到req.Form中
})
// 然后添加一些特定的URL处理程序。

在Go文档中,它说长的Pattern比短的Pattern优先级更高。我想在所有处理程序之前运行一些代码(解析id,清理路径等)。

我不想放弃defaultmux的功能。我应该重新定义一个全新的路由,还是使用http.NewServeMux()?如果我使用http.NewServeMux(),我应该如何添加一些内容同时保留这些功能?

英文:

i have viewed source code of mux,but i just want something simple ,not using all features.

i wanna get value of "id" in the url like /url/{id},setting the value in the req.Form and clean the path like mux.

code like

	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.

in go doc ,it says long Pattern will take higher priority than short Pattern.
and i want to run something(parse id , clean path etc) before all handlers.

i don't want to give up the features of defaultmux. should i redefine a brand new route,or use http.NewServeMux()? if i use http.NewServerMux(),how should i do to add something while keeping the features?

答案1

得分: 2

我们在生产环境中已经使用了一年多的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, "要监听的端口")
  flag.UintVar(&port, "p", 8000, "要监听的端口")
}

func main() {
  flag.Parse()

  // 获取当前工作目录
  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))
}

告诉我你想要的路由是什么,我可以给你一个更具体的示例来满足你的需求。

英文:

We have used http://www.gorillatoolkit.org/pkg/mux for over a year in our production stack and have been very happy with it.

For some really simple sites I host I use the built in routing something like this:

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))
}

Let me know what you want your routes to be and I could give you a more specific example to what you are looking for.

huangapple
  • 本文由 发表于 2014年2月24日 12:27:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/21978883.html
匿名

发表评论

匿名网友

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

确定