Hun ssh
Hun ssh

Reputation: 3

go chi router with url parameters and mysql db not working properly

I am new to golang and working on a restful service in golang using chi. I am trying to create a route as below:

    func NewRouter(dm *storage.DatabaseManager) chi.Router {
    var router = chi.NewRouter()
     router.Method("POST", "/restaurant/search?name={name}", 
     &SearchRestaurants{DB: dm})

}

Here is how I fetch from mysql db:

    func (rm *RestaurantManager) SearchRestaurantsFromDB(name string) 
   ([]Restaurant, error) {
    var restaurants []Restaurant
   var stmt = fmt.Sprintf(`SELECT * FROM %s WHERE name=%s `, 
   rm.tableName, name)
   var err error
  if err = rm.Select(&restaurants, stmt); err != nil {
    return nil, err
}
return restaurants, nil

}

...and how I get from these:

func (h SearchRestaurants) ServeHTTP(w http.ResponseWriter, r 
*http.Request) {
 var err error
 var result []storage.Restaurant
 name := r.URL.Query().Get("name")
 if result, err = h.DB.SearchRestaurantsFromDB(name); err != nil {
    log.Fatal("Database Error: ", err)
}
fmt.Print(result)
api.WriteJSON(w, result)
log.Print(r.RequestURI)

}

But I try to hit this endpoint but I get a 404 not found: http://localhost:8000/project/restaurant/search?name={n}

May I know the issue here?

P.S.there is router.Mount("/project/", restaurant.NewRouter(dm)) in the main func.

Upvotes: 0

Views: 3488

Answers (1)

Lucas Katayama
Lucas Katayama

Reputation: 4580

I don't know chi but I think you misundestood the router path

You actually don't use query params to define the path router, the variables on path like {n} is for path params. What you are using is a Query param.

See the difference here :

Path Param

Access from: http://localhost:3333/name/JohnDoe

func main() {
  r := chi.NewRouter()

  r.Get("/name/{name}", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("hi" + chi.URLParam(r, "name")))
  })

  http.ListenAndServe(":3333", r)
}

Query Param

Access from: http://localhost:3333/name?name=JohnDoe


func main() {
  r := chi.NewRouter()

  r.Get("/name", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("hi" + r.URL.Query().Get("name")))
  })

  http.ListenAndServe(":3333", r)
}

Upvotes: 7

Related Questions