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

查看:21
本文介绍了Go 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 库的问题.我从基本问题开始,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, ""
        }
}

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

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