Why does r.PathValue() not work for subrouters in Go 1.22?

I’m writing an API with some basic CRUD operations, and I’d like to be able to have my “photos” resource as a sub-resource of my “events” (i.e. requests are made against api/events/photos). I also have a dedicated /api/photos endpoint for whatever else, but I really want to be able to use the URL parameters for the event itself in getting the photos as this seems more sensible to me. However, after some finagling I’ve gotten subrouting to work acceptably, but the r.PathValue("eventId") within my subrouting handler simply returns an empty string.

In one file, I sew all of my routers together, initializing each http.ServeMux with the routes from that service.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>rootRouter := http.NewServeMux()
// supply routes from service-specific route additions
// - Photo Routing -
photoStore := photos.NewStore(s.db)
photoHandler := photos.NewHandler(photoStore)
photoRouter := http.NewServeMux()
photoHandler.RegisterRoutes(photoRouter)
rootRouter.Handle("/photos/", http.StripPrefix("/photos", photoRouter))
// sub router
photoSubRouter := http.NewServeMux()
photoHandler.RegisterSubRoutes(photoSubRouter)
// - Event Routing -
eventStore := events.NewStore(s.db)
eventHandler := events.NewHandler(eventStore)
eventRouter := http.NewServeMux()
eventHandler.RegisterRoutes(eventRouter, photoSubRouter)
rootRouter.Handle("/events/", http.StripPrefix("/events", eventRouter))
</code>
<code>rootRouter := http.NewServeMux() // supply routes from service-specific route additions // - Photo Routing - photoStore := photos.NewStore(s.db) photoHandler := photos.NewHandler(photoStore) photoRouter := http.NewServeMux() photoHandler.RegisterRoutes(photoRouter) rootRouter.Handle("/photos/", http.StripPrefix("/photos", photoRouter)) // sub router photoSubRouter := http.NewServeMux() photoHandler.RegisterSubRoutes(photoSubRouter) // - Event Routing - eventStore := events.NewStore(s.db) eventHandler := events.NewHandler(eventStore) eventRouter := http.NewServeMux() eventHandler.RegisterRoutes(eventRouter, photoSubRouter) rootRouter.Handle("/events/", http.StripPrefix("/events", eventRouter)) </code>
rootRouter := http.NewServeMux()
// supply routes from service-specific route additions
// - Photo Routing -
photoStore := photos.NewStore(s.db)
photoHandler := photos.NewHandler(photoStore)

photoRouter := http.NewServeMux()
photoHandler.RegisterRoutes(photoRouter)
rootRouter.Handle("/photos/", http.StripPrefix("/photos", photoRouter))

// sub router
photoSubRouter := http.NewServeMux()
photoHandler.RegisterSubRoutes(photoSubRouter)

// - Event Routing -
eventStore := events.NewStore(s.db)
eventHandler := events.NewHandler(eventStore)

eventRouter := http.NewServeMux()
eventHandler.RegisterRoutes(eventRouter, photoSubRouter)
rootRouter.Handle("/events/", http.StripPrefix("/events", eventRouter))

For my event routing, I pass in a primary router and a subrouter for handling the the subresource specifically, just so all of my photo endpoint logic can remain within that service.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
func (h *Handler) RegisterRoutes(router *http.ServeMux, subRouter *http.ServeMux) {
router.HandleFunc("GET /{$}", h.handleEventsGet)
router.HandleFunc("GET /{eventId}", h.handleEventGetByID)
router.Handle("/{eventId}/photos/", subRouter)
</code>
<code> func (h *Handler) RegisterRoutes(router *http.ServeMux, subRouter *http.ServeMux) { router.HandleFunc("GET /{$}", h.handleEventsGet) router.HandleFunc("GET /{eventId}", h.handleEventGetByID) router.Handle("/{eventId}/photos/", subRouter) </code>

func (h *Handler) RegisterRoutes(router *http.ServeMux, subRouter *http.ServeMux) {
    router.HandleFunc("GET /{$}", h.handleEventsGet)
    router.HandleFunc("GET /{eventId}", h.handleEventGetByID)
    router.Handle("/{eventId}/photos/", subRouter)

This handler (handlePhotosGetByEventID) is just a demonstration, but from testing it I do indeed get a URL path that includes the eventId. However, the call to r.PathValue("eventId") simply returns an empty string. I’ve considered doing some sort of string split thing and manually determining what characters should be the eventId but that feels less secure, so I wanted to see if this was just a limitation of the routers themselves, as opposed to my incompetence.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
func (h *Handler) RegisterSubRoutes(router *http.ServeMux) {
router.HandleFunc("GET /", h.handlePhotosGetByEventID)
router.HandleFunc("GET /{photoId}", h.handlePhotoGetByID)
}
func (h *Handler) handlePhotosGetByEventID(w http.ResponseWriter, r *http.Request) {
log.Println("Hello! You've requested the photos associated with this event")
log.Println(r.URL.Path)
id, err := strconv.Atoi(r.PathValue("eventId"))
// malformed id unable to be converted
if err != nil {
utils.WriteError(w, http.StatusBadRequest, err)
return
}
log.Println("Event ID: ", id, " But also I'm photos")
if err := utils.Encode(w, 200, map[string]string{"event": strconv.Itoa(id), "photos": "many"}); err != nil {
utils.WriteError(w, http.StatusInternalServerError, err)
return
}
}
</code>
<code> func (h *Handler) RegisterSubRoutes(router *http.ServeMux) { router.HandleFunc("GET /", h.handlePhotosGetByEventID) router.HandleFunc("GET /{photoId}", h.handlePhotoGetByID) } func (h *Handler) handlePhotosGetByEventID(w http.ResponseWriter, r *http.Request) { log.Println("Hello! You've requested the photos associated with this event") log.Println(r.URL.Path) id, err := strconv.Atoi(r.PathValue("eventId")) // malformed id unable to be converted if err != nil { utils.WriteError(w, http.StatusBadRequest, err) return } log.Println("Event ID: ", id, " But also I'm photos") if err := utils.Encode(w, 200, map[string]string{"event": strconv.Itoa(id), "photos": "many"}); err != nil { utils.WriteError(w, http.StatusInternalServerError, err) return } } </code>

func (h *Handler) RegisterSubRoutes(router *http.ServeMux) {
    router.HandleFunc("GET /", h.handlePhotosGetByEventID)
    router.HandleFunc("GET /{photoId}", h.handlePhotoGetByID)
}

func (h *Handler) handlePhotosGetByEventID(w http.ResponseWriter, r *http.Request) {
    log.Println("Hello! You've requested the photos associated with this event")
    log.Println(r.URL.Path)
    id, err := strconv.Atoi(r.PathValue("eventId"))
    // malformed id unable to be converted
    if err != nil {
        utils.WriteError(w, http.StatusBadRequest, err)
        return
    }
    log.Println("Event ID: ", id, " But also I'm photos")
    if err := utils.Encode(w, 200, map[string]string{"event": strconv.Itoa(id), "photos": "many"}); err != nil {
        utils.WriteError(w, http.StatusInternalServerError, err)
        return
    }
}

What am I missing here?

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật