duanpu2272 2017-06-04 08:15
浏览 68

Golang分层路由

I want to make RESTful API which has multi layer route like :

/api/auhtorization/getUserdata

where api stands for webservice name, auhtorization stands for a function to check validation of token. and getUserdata stands for a function that get specific user data ( if only request past authorization level )

func main(){
   http.HandleFunc("api/", func(rw, req){
      http.HandleFunc("authorization/", func(){

         if (auth passed)
         {
            http.HandleFunc("getUserdata", getUserFunction())
         }

      })

   })
}

I know above code isn't a good example but I seek for best practice or framework for doing this. Any answer will be highly appreciated!

  • 写回答

2条回答 默认 最新

  • doubiao1734 2017-06-05 13:33
    关注

    Your first (outmost) call to http.HandleFunc is correct - it maps a route to a handler function. The rest of the code implies a misunderstanding of how that works, though. The handler function will be called when a request matching that route comes in; when a handling a request is not the time to register additional routes, because route registration is not request-specific, and it's too late to modify the routing table for the current request. The last call makes even less sense: you can't register a route based on whether the current request is authorized. As soon as one authorized request comes in, that route will be registered for all future requests, regardless of whether those requests are authorized, and will not make any different for the current request.

    What you want, most likely, is to replace both of the nested calls to http.HandleFunc with calls to handler methods, e.g.:

    func main(){
        http.HandleFunc("/api/", func(rw, req){
            if strings.HasPrefix(req.URL.Path, "/api/authorization") {
                doAuthorization(rw,req)
            }
        }
    }
    
    func doAuthorization(rw http.ResponseWriter, req *http.Request) {
        if authPassed && strings.HasPrefix(req.URL.Path, "/api/authorization/getUserdata") {
            getUserFunction(rw,req)
        }
    }
    

    Or, alternatively, use the router for all of it:

    func main() {
        http.HandleFunc("/api", doApi)
        http.HandleFunc("/api/authorization", doAuthorization)
        http.HandleFunc("/api/authorization/getUserdata", getUserFunction)
    }
    
    func doApi(rw, req) {
        // Whatever you'd do for a call to "/api" itself
    }
    
    func doAuthorization(rw http.ResponseWriter, req *http.Request) {
        // Whatever you'd do for a call to "/api/authorization" itself
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀