Is it possible to know what route is used in HandleFunc

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

Is it possible to know what route is used in HandleFunc

问题

我正在使用net/http包中的http.HandleFunc("/resource", resource.Handle),我想知道是否有一种方法可以查看到达resource.Handle的路由(在这种情况下是/resource)?还是说我必须创建一个Mux来实现这个功能?

我想知道这个是为了从URL路径中提取资源,以便进行一些操作...

英文:

I am using http.HandleFunc("/resource", resource.Handle) from the package net/http and I was wondering if there was a way to see what route (in this case /resource) is used to get you to resource.Handle? Or do I have to create a Mux for this?

I'd like to know this to extract the resource from the url path to do some magic with it...

答案1

得分: 3

使用request.URL.Path来获取访问处理程序的路径。

英文:

http://golang.org/pkg/net/http/#Request

Use request.URL.Path to get the path used to access the handler.

答案2

得分: 3

是的,你可以这样做:

  • 使用HandleFunc方法使用的DefaultServeMux
  • 构造一个假的http.Request

例如:

package main

import (
	"fmt"
	"net/http"
	"net/url"
)

func main() {

	theUrl, err := url.Parse("/response")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	http.HandleFunc("/response", func(w http.ResponseWriter, r *http.Request) {

	})

	handler, path := http.DefaultServeMux.Handler(&http.Request{Method: "GET", URL: theUrl})

	fmt.Println(handler, path)

}

可以在Go Playground上查看示例。

英文:

Yes you can

The main points to do:

  • Use the DefaultServeMux used by the HandleFunc method.
  • Construct a fake http.Request

For Example:

package main

import (
	"fmt"
	"net/http"
	"net/url"
)

func main() {

	theUrl, err := url.Parse("/response")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	http.HandleFunc("/response", func(w http.ResponseWriter, r *http.Request) {

	})

	handler, path := http.DefaultServeMux.Handler(&http.Request{Method: "GET", URL: theUrl})

	fmt.Println(handler, path)

}

see this Go Playground

huangapple
  • 本文由 发表于 2014年5月28日 02:47:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/23896805.html
匿名

发表评论

匿名网友

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

确定