Iterating through key and values of golang struct not giving same result for some reason

StackOverflow https://stackoverflow.com/questions/23550851

  •  18-07-2023
  •  | 
  •  

Pergunta

I have a golang map like this:

var routes map[string]*rest.Route

I've added a bunch of key/values to it like so:

routes["Index"] = &rest.Route{"GET", "/", handlers.GetIndex}
routes["ListStudents"] = &rest.Route{"GET", "/students", handlers.ListStudents}
routes["ViewStudent"] = &rest.Route{"GET", "/students/:id", handlers.ViewStudent}
routes["CreateStudent"] = &rest.Route{"POST", "/students", handlers.CreateStudent}
routes["UpdateStudent"] = &rest.Route{"PUT", "/students/:id", handlers.UpdateStudent}
routes["DeleteStudent"] = &rest.Route{"DELETE", "/students/:id", handlers.DeleteStudent}

When I call a function, SetRoute on individual values, it works, like so:

handler.SetRoutes(routes["Index"])

However, when I try to iterate through the map with range, it doesn't work. I know it doesn't work because of testing that happens afterwards. However, if I print out the keys and values as I call SetRoute, I can see that the keys and values are what I expect. Specifically, the values are addresses.

// This doesn't work, even though printing out k,v shows nothing wrong...
for k, v := range routes {
    err := handler.SetRoutes(v)
    fmt.Println(k)
    fmt.Println(v)
    if err != nil {
        log.Fatal(err)
    }
}

Printing it out shows:

Index
&{GET / 0x442250}
ListStudents
&{GET /students 0x4422f0}
ViewStudent
&{GET /students/:id 0x4427c0}
UpdateStudent
&{PUT /students/:id 0x443520}
DeleteStudent
&{DELETE /students/:id 0x443a30}
CreateSchool
&{POST /schools 0x444660}
CreateStudent
&{POST /students 0x442ed0}
ListSchools
&{GET /schools 0x443d50}
ViewSchool
&{GET /schools/:id 0x444200}
UpdateSchool
&{PUT /schools/:id 0x444cc0}
DeleteSchool
&{DELETE /schools/:id 0x4453b0}

What am I doing wrong?

Foi útil?

Solução

It seems that handler.SetRoutes is variadic. You can pass multiple routes to it.

This should work:

routes := []rest.Route{
  rest.Route{"GET", "/", handlers.GetIndex},
  rest.Route{"GET", "/students", handlers.ListStudents},
  // more routes
}
handler.SetRoutes(routes...)

Outras dicas

So it turns out this isn't a golang issue, but a go-json-rest issue, which is the library I'm using to create a RESTful API in Go.

Essentially, the SetRoutes function isn't ADDING each subsequent value, but simply replacing. So no matter how many times I call it, only the last call will actually be persisted.

SetRoutes was supposed to be called only once. Also this interface is deprecated. you should use the v3 API, which I think is less confusing:

    api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
    // your routes here ...
)
if err != nil {
    log.Fatal(err)
}
api.SetApp(router)
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top