Gorilla/Mux中的路径参数具有任意深度。

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

Path parameters with arbitrary depth in Gorilla/Mux

问题

我一直在努力创建一个API,它可以通过读取JSON文件的内容来发送JSON响应。

data.json

{
    "data_1" : {
        "depth2" : {
            "depth3" : "data 1的值"
        }
    },
    "data_2" : {
        "depth2" : {
            "depth3" : "data 2的值"
        }
    },
    "data_3" : {
        "depth2" : {
            "depth3" : "data 3的值"
        }
    }
}

我想创建一个动态嵌套路由系统,当客户端请求/api/data_1/depth2时,我希望响应如下:

{
   "depth3" : "data 1的值"
}

请注意,请求路径可以无限深...例如/api/data_1/depth2/api/data_1/depth2/depth3甚至/api/data_1/depth2/depth3/depth4(取决于data.json),这意味着我不能像/api/{var_1}/{var_2}这样设置路径,因为它的深度是固定的(即2层)。

我需要在我的代码中解决这个问题。

server.go

package main

import (
   ....
   ....
)

func main() {

  // 我在项目中使用Gorilla/mux
  router := mux.NewRouter()

  // 处理请求
  router.HandleFunc("/api/这里应该写什么?", ApiHandler)

  // 启动服务器
  log.Fatal(http.ListenAndServe(":8080", router))
}

我已经有一个函数NestedLookUp(data map[string]interface{}, key[]string),它将在ApiHandler中调用,如果键是["data_1", "depth2", ...],它将从嵌套的map[string]interface{}中返回数据。我只是在弄清楚router的正确路由方面遇到了问题。

英文:

I've been working on making a API that would send a json response by reading contents from a json file

data.json

{
    "data_1" : {
        "depth2" : {
            "depth3" : "Value of data 1"
        }
    },
    "data_2" : {
        "depth2" : {
            "depth3" : "Value of data 2"
        }
    },
    "data_3" : {
        "depth2" : {
            "depth3" : "Value of data 3"
        }
    }
}

I want to make a dynamic nested routing system where if the client requests for, say /api/data_1/depth2 I want the response to be like

{
   "depth3" : "Value of data 1"
}

Let me make it clear that the request path can be indefinitely deep... like /api/data_1/depth2 or /api/data_1/depth2/depth3 or even /api/data_1/depth2/depth3/depth4 (depending upon data.json) which means I cant make my paths like /api/{var_1}/{var_2} since its depth is fixed (ie 2 layers)

I need help in solving this in my code

server.go

package main

import (
   ....
   ....
)

func main() {

  // I'm using Gorilla/mux in my project
  router := mux.NewRouter()

  // Handle requests 
  router.HandleFunc("/api/what_should_I_write_here?", ApiHandler)

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

I already have a function NestedLookUp(data map[string]interface{}, key[]string) that will return data from a nested map[string]interface{} if the key is ["data_1", "depth2" ...] called inside ApiHandler. I only have problem figuring the correct route for my router

答案1

得分: 2

只是为了详细说明我的评论,如果存在无限深度,为什么不这样获取深度路径呢?

func main() {
    r := mux.NewRouter()
    sub := r.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
        q := r.URL.Query()
        depthPath := q.Get("depthPath")
        depthPathArr := strings.Split(depthPath, "-")

        // depthPath []string{1, 2, 3, 4, 5}
        // 编写一个函数来遵循 depthPath
    })
    srv := &http.Server{
        Handler:      r,
        Addr:         "localhost:7890",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }
    log.Fatal(srv.ListenAndServe())
}
英文:

Just to elaborate my comment, if there's an indefinite depth, why don't you get your depth path like so?

func main() {
    r := mux.NewRouter()
    sub := r.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
        q := r.URL.Query()
        depthPath := q.Get("depthPath")
        depthPathArr := strings.Split(depthPath, "-")

        // depthPath []string{1, 2, 3, 4, 5}
        // write function that follow the depthPath
    })
    srv := &http.Server{
        Handler: r,
        Addr: "localhost:7890",
        WriteTimeout: 15 * time.Second,
        ReadTimeout: 15 * time.Second,
    }
    log.Fatal(srv.ListenAndServe())
}

huangapple
  • 本文由 发表于 2022年7月6日 18:46:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/72882193.html
匿名

发表评论

匿名网友

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

确定