转到url参数映射 [英] Go url parameters mapping

查看:81
本文介绍了转到url参数映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在本机Go中是否存在用于本机url参数的本机方式?

Is there a native way for inplace url parameters in native Go?

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

For Example, if I have a URL: http://localhost:8080/blob/123/test I want to use this URL as /blob/{id}/test.

这不是有关查找go库的问题.我从一个基本问题开始,它本身是否提供了本机执行此操作的基本工具.

This is not a question about finding go libraries. I am starting with the basic question, does go itself provide a basic facility to do this natively.

推荐答案

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

There is no built in simple way to do this, however, it is not hard to do.

这就是我的方法,而无需添加特定的库.它放置在一个函数中,以便您可以在请求处理程序中调用一个简单的getCode()函数.

This is how I do it, without adding a particular library. It is placed in a function so that you can invoke a simple getCode() function within your request handler.

基本上,您只是将r.URL.Path拆分为多个部分,然后分析这些部分.

Basically you just split the r.URL.Path into parts, and then analyse the parts.

// 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, ""
        }
}

这篇关于转到url参数映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆