helper.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package multiModulePage
  2. import (
  3. "errors"
  4. "net/url"
  5. "strconv"
  6. "github.com/cryptix/go/logging"
  7. "github.com/gorilla/mux"
  8. )
  9. func NewURLTo(appRouter *mux.Router) func(string, ...interface{}) *url.URL {
  10. l := logging.Logger("helper.URLTo") // TOOD: inject in a scoped way
  11. return func(routeName string, ps ...interface{}) *url.URL {
  12. route := appRouter.Get(routeName)
  13. if route == nil {
  14. l.Log("msg", "no such route", "route", routeName, "params", ps)
  15. return &url.URL{}
  16. }
  17. var params []string
  18. for _, p := range ps {
  19. switch v := p.(type) {
  20. case string:
  21. params = append(params, v)
  22. case int:
  23. params = append(params, strconv.Itoa(v))
  24. case int64:
  25. params = append(params, strconv.FormatInt(v, 10))
  26. default:
  27. l.Log("msg", "invalid param type", "param", p, "route", routeName)
  28. logging.CheckFatal(errors.New("invalid param"))
  29. }
  30. }
  31. u, err := route.URLPath(params...)
  32. if err != nil {
  33. l.Log("msg", "failed to create URL",
  34. "route", routeName,
  35. "params", params,
  36. "error", err)
  37. return &url.URL{}
  38. }
  39. return u
  40. }
  41. }