plgd-dev / go-coap

Implementation of CoAP Server & Client in Go

Home Page:https://coap.technology

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

mux.Router can't handle root path or no path ("/")

palsivertsen opened this issue · comments

Setting up a handler for the root path ("/") or no path ("") does not work.

Example:

package main

import (
	"bytes"
	"context"
	"log"
	"time"

	"github.com/plgd-dev/go-coap/v3"
	"github.com/plgd-dev/go-coap/v3/message"
	"github.com/plgd-dev/go-coap/v3/message/codes"
	"github.com/plgd-dev/go-coap/v3/mux"
	"github.com/plgd-dev/go-coap/v3/udp"
)

func main() {
	go serve()
	time.Sleep(time.Second)

	testPath("")
	testPath("/")
	testPath("/a")
}

func testPath(path string) {
	co, err := udp.Dial("localhost:5688")
	if err != nil {
		log.Fatalf("Error dialing: %v", err)
	}

	resp, err := co.Get(context.Background(), path)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	log.Printf("Response for %q: %s", path, resp.Code())
}

func serve() {
	r := mux.NewRouter()
	r.Handle("", mux.HandlerFunc(handleA))
	r.Handle("/", mux.HandlerFunc(handleA))
	r.Handle("/a", mux.HandlerFunc(handleA))

	log.Fatal(coap.ListenAndServe("udp", ":5688", r))
}

func handleA(w mux.ResponseWriter, r *mux.Message) {
	err := w.SetResponse(codes.Content, message.TextPlain, bytes.NewReader([]byte("hello world")))
	if err != nil {
		log.Printf("cannot set response: %v", err)
	}
}

Expected output:

2023/05/03 20:16:05 Response for "": Content
2023/05/03 20:16:05 Response for "/": Content
2023/05/03 20:16:05 Response for "/a": Content

Actual output:

2023/05/03 20:16:05 Response for "": NotFound
2023/05/03 20:16:05 Response for "/": NotFound
2023/05/03 20:16:05 Response for "/a": Content

This is a bug. Thx for reporting.

Should be fixed by PR #498

#498 did not resolve this issue.

Tested using github.com/plgd-dev/go-coap/v3 v3.1.6-0.20231026111111-38e3fa428a85