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
}