Skip to content

plgd-dev/go-coap

Repository files navigation

Build Status codecov Go Report FOSSA Status

CoAP Client and Server for go

Features supported:

Samples

Simple

Server UDP/TCP

	// Server
	// See /examples/simple/server/main.go
	func handleA(w mux.ResponseWriter, req *message.Message) {
		log.Printf("got message in handleA:  %+v from %v\n", req, w.ClientConn().RemoteAddr())
		err := w.SetResponse(codes.GET, message.TextPlain, bytes.NewReader([]byte("hello world")))
		if err != nil {
			log.Printf("cannot set response: %v", err)
		}
	}

	func main() {
		m := mux.NewServeMux()
		m.Handle("/a", mux.HandlerFunc(handleA))
		m.Handle("/b", mux.HandlerFunc(handleB))

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

		
		// for tcp
		// log.Fatal(coap.ListenAndServe("tcp", ":5688",  m))

		// for tcp-tls
		// log.Fatal(coap.ListenAndServeTLS("tcp-tls", ":5688", &tls.Config{...}, m))

		// for udp-dtls
		// log.Fatal(coap.ListenAndServeDTLS("udp-dtls", ":5688", &dtls.Config{...}, m))
	}

Client

	// Client
	// See /examples/simpler/client/main.go
	func main() {
		co, err := udp.Dial("localhost:5688")
		
		// for tcp
		// co, err := tcp.Dial("localhost:5688")
		
		// for tcp-tls
		// co, err := tcp.Dial("localhost:5688", tcp.WithTLS(&tls.Config{...}))

		// for dtls
		// co, err := dtls.Dial("localhost:5688", &dtls.Config{...}))

		if err != nil {
			log.Fatalf("Error dialing: %v", err)
		}
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		defer cancel()
		resp, err := co.Get(ctx, "/a")
		if err != nil {
			log.Fatalf("Cannot get response: %v", err)
			return
		}
		log.Printf("Response: %+v", resp)
	}

Observe / Notify

Server

Look to examples/observe/server/main.go

Client

Look to examples/observe/client/main.go

Multicast

Server

Look to examples/mcast/server/main.go

Client

Look to examples/mcast/client/main.go

Contributing

In order to run the tests that the CI will run locally, the following two commands can be used to build the Docker image and run the tests. When making changes, these are the tests that the CI will run, so please make sure that the tests work locally before committing.

$ docker build . --network=host -t go-coap:build --target build
$ docker run --mount type=bind,source="$(pwd)",target=/shared,readonly --network=host go-coap:build go test './...'

License

Apache 2.0

FOSSA Status