去url参数映射

问题描述 投票:20回答:5

在本地Go中是否存在本地url参数的原生方式?

例如,如果我有一个URL:http://localhost:8080/blob/123/test我想将此URL用作/blob/{id}/test

这不是关于找到go库的问题。我从基本问题开始,本身就提供了一个基本的设施来做这个本地。

go routes url-mapping
5个回答
15
投票

没有内置的简单方法可以做到这一点,但是,这并不难。

这是我如何做到这一点,而不添加特定的库。它被放置在一个函数中,以便您可以在请求处理程序中调用一个简单的getCode()函数。

基本上你只是将r.URL.Path分成几部分,然后分析部分。

// Extract a code from a URL. Return the default code if code
// is missing or code is not a valid number.
func getCode(r *http.Request, defaultCode int) (int, string) {
        p := strings.Split(r.URL.Path, "/")
        if len(p) == 1 {
                return defaultCode, p[0]
        } else if len(p) > 1 {
                code, err := strconv.Atoi(p[0])
                if err == nil {
                        return code, p[1]
                } else {
                        return defaultCode, p[1]
                }
        } else {
                return defaultCode, ""
        }
}

11
投票

好吧,没有外部库,你不能,但我可以推荐两个优秀的:

  1. httprouter - https://github.com/julienschmidt/httprouter - 非常快,非常轻巧。它比标准库的路由器更快,并且每次调用创建0个分配,这在GCed语言中很棒。
  2. 大猩猩Mux - http://www.gorillatoolkit.org/pkg/mux - 非常受欢迎,漂亮的界面,漂亮的社区。

httprouter的示例用法:

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
    router := httprouter.New()
    router.GET("/hello/:name", Hello)

    log.Fatal(http.ListenAndServe(":8080", router))
}

2
投票

如下编写自己的url生成器(稍微扩展net/url)怎么样?

// --- This is how does it work like --- //
url, _ := rest.NewURLGen("http", "stack.over.flow", "1234").
    Pattern(foo/:foo_id/bar/:bar_id).
    ParamQuery("foo_id", "abc").
    ParamQuery("bar_id", "xyz").
    ParamQuery("page", "1").
    ParamQuery("offset", "5").
    Do()

log.Printf("url: %s", url) 
// url: http://stack.over.flow:1234/foo/abc/bar/xyz?page=1&offset=5

// --- Your own url generator would be like below --- //
package rest

import (
    "log"
    "net/url"
    "strings"

    "straas.io/base/errors"

    "github.com/jinzhu/copier"
)

// URLGen generates request URL
type URLGen struct {
    url.URL

    pattern    string
    paramPath  map[string]string
    paramQuery map[string]string
}

// NewURLGen new a URLGen
func NewURLGen(scheme, host, port string) *URLGen {
    h := host
    if port != "" {
        h += ":" + port
    }

    ug := URLGen{}
    ug.Scheme = scheme
    ug.Host = h
    ug.paramPath = make(map[string]string)
    ug.paramQuery = make(map[string]string)

    return &ug
}

// Clone return copied self
func (u *URLGen) Clone() *URLGen {
    cloned := &URLGen{}
    cloned.paramPath = make(map[string]string)
    cloned.paramQuery = make(map[string]string)

    err := copier.Copy(cloned, u)
    if err != nil {
        log.Panic(err)
    }

    return cloned
}

// Pattern sets path pattern with placeholder (format `:<holder_name>`)
func (u *URLGen) Pattern(pattern string) *URLGen {
    u.pattern = pattern
    return u
}

// ParamPath builds path part of URL
func (u *URLGen) ParamPath(key, value string) *URLGen {
    u.paramPath[key] = value
    return u
}

// ParamQuery builds query part of URL
func (u *URLGen) ParamQuery(key, value string) *URLGen {
    u.paramQuery[key] = value
    return u
}

// Do returns final URL result.
// The result URL string is possible not escaped correctly.
// This is input for `gorequest`, `gorequest` will handle URL escape.
func (u *URLGen) Do() (string, error) {
    err := u.buildPath()
    if err != nil {
        return "", err
    }
    u.buildQuery()

    return u.String(), nil
}

func (u *URLGen) buildPath() error {
    r := []string{}
    p := strings.Split(u.pattern, "/")

    for i := range p {
        part := p[i]
        if strings.Contains(part, ":") {
            key := strings.TrimPrefix(p[i], ":")

            if val, ok := u.paramPath[key]; ok {
                r = append(r, val)
            } else {
                if i != len(p)-1 {
                    // if placeholder at the end of pattern, it could be not provided
                    return errors.Errorf("placeholder[%s] not provided", key)
                }
            }
            continue
        }
        r = append(r, part)
    }

    u.Path = strings.Join(r, "/")
    return nil
}

func (u *URLGen) buildQuery() {
    q := u.URL.Query()
    for k, v := range u.paramQuery {
        q.Set(k, v)
    }
    u.RawQuery = q.Encode()
}

0
投票

没有标准库没办法。为什么你不想尝试一些图书馆?我认为使用它并不是那么难,只需去吧bla bla bla

我用Beego。它的MVC风格。


-5
投票

如果你需要一个框架并且你认为它会慢,因为它比路由器或网络/ http“更大”,那你就错了。

根据所有基准测试,Iris是迄今为止最快的网络框架。

安装方式

  go get gopkg.in/kataras/iris.v6

使用虹膜,Django模板变得简单:

import (
    "gopkg.in/kataras/iris.v6"
    "gopkg.in/kataras/iris.v6/adaptors/httprouter"
    "gopkg.in/kataras/iris.v6/adaptors/view" // <-----

)

func main() {

    app := iris.New()
    app.Adapt(iris.DevLogger())
    app.Adapt(httprouter.New()) // you can choose gorillamux too
    app.Adapt(view.Django("./templates", ".html")) // <-----

    // RESOURCE: http://127.0.0.1:8080/hi
    // METHOD: "GET"
    app.Get("/hi", hi)

    app.Listen(":8080")
}

func hi(ctx *iris.Context){
   ctx.Render("hi.html", iris.Map{"Name": "iris"})
}
© www.soinside.com 2019 - 2024. All rights reserved.