coap

package module
v3.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 12 Imported by: 17 modules, 15 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go-CoAP

Build Status Quality Gate Status Coverage FOSSA Status contributors GitHub stars GitHub license GoDoc

The Constrained Application Protocol (CoAP) is a specialized web transfer protocol for use with constrained nodes and constrained networks in the Internet of Things. The protocol is designed for machine-to-machine (M2M) applications such as smart energy and building automation.

The go-coap provides servers and clients for DTLS, TCP-TLS, UDP, TCP in golang language.

Features

  • CoAP over UDP RFC 7252.
  • Observe resources in CoAP RFC 7641
  • Block-wise transfers in CoAP RFC 7959
  • CoAP NoResponse option in CoAP RFC 7967
  • FETCH, PATCH, and iPATCH methods RFC 8132
  • CoAP over TCP/TLS RFC 8323
  • Too many requests response code RFC 8516
  • Object Security for Constrained RESTful Environments (OSCORE) RFC 8613
  • CoAP Echo and Request-Tag options RFC 9175
  • Experimental Q-Block datagram transfers RFC 9177
  • CoAP over DTLS pion/dtls
  • request multiplexer
  • multicast

Requirements

  • Go 1.26 or higher

Server handshake limits

DTLS and TCP-TLS servers allow at most 1,024 concurrent handshakes by default, with a 30-second handshake timeout. At the limit, the oldest pending handshake is canceled and its connection starts closing. A new handshake is admitted when any pending handshake releases a slot; the evicted handshake remains counted until its cleanup finishes. options.WithMaxPendingHandshakes and options.WithHandshakeTimeout configure these settings; a zero limit removes the bound and a nonpositive timeout disables the timeout. Unlimited handshakes can exhaust server resources.

Evicted handshakes and failures other than cancellation or closed-connection errors are reported through the configured error callback with handshake failed. TCP-TLS completes the handshake before creating the CoAP session and calling OnNewConn. Plain TCP is unaffected. A sustained flood can still prevent slow handshakes from completing; large fleets may need a higher limit for simultaneous reconnects.

Experimental Q-Block transfers

Q-Block is opt-in for UDP/DTLS; existing blockwise defaults are unchanged. See the QBlockwise guide for configuration, limits, libcoap interoperability tests for Blockwise and Q-Block transfers (including the RFC 8132 methods), and a runnable client / server example.

OSCORE

OSCORE protects CoAP messages using application-provisioned security contexts. See the OSCORE guide for configuration, sequence persistence, supported transports, and limitations. A runnable UDP client/server example demonstrates protected requests and durable sender/replay state. Avoid volatile sender sequence state in production: restarting with the same sender key can reuse AEAD nonces.

Samples

FETCH, PATCH, and iPATCH (RFC 8132)

The simple client and server demonstrate all three methods on /object: FETCH selects a JSON field, PATCH appends with JSON Patch, and iPATCH replaces the value with JSON Merge Patch. The Q-Blockwise client and server demonstrate the methods with large payloads; their application-defined octet-stream behavior uses FETCH to read, PATCH to append, and iPATCH to replace data.

Run either pair in separate terminals:

go run ./examples/simple/server
go run ./examples/simple/client
go run ./examples/qblockwise/server
go run ./examples/qblockwise/client
Simple
Server UDP/TCP
    // Server

    // Middleware function, which will be called for each request.
    func loggingMiddleware(next mux.Handler) mux.Handler {
        return mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) {
            log.Printf("ClientAddress %v, %v\n", w.Conn().RemoteAddr(), r.String())
            next.ServeCOAP(w, r)
        })
    }

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

    func main() {
        r := mux.NewRouter()
        r.Use(loggingMiddleware)
        r.Handle("/a", mux.HandlerFunc(handleA))
        r.Handle("/b", mux.HandlerFunc(handleB))

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


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

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

        // for udp-dtls (deprecated: *dtls.Config is deprecated in pion/dtls v3, prefer options-based API)
        // log.Fatal(coap.ListenAndServeDTLS("udp", ":5688", &dtls.Config{...}, r))

        // for udp-dtls (options-based API — pion/dtls v3)
        // log.Fatal(coap.ListenAndServeDTLS("udp", ":5688",
        //     net.NewDTLSServerOptions(dtls.WithPSK(...), dtls.WithCertificates(...)), r))
    }
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 (deprecated: *dtls.Config is deprecated in pion/dtls v3, prefer options-based API)
        // co, err := dtls.Dial("localhost:5688", &dtls.Config{...})

        // for dtls (options-based API — pion/dtls v3)
        // co, err := dtls.Dial("localhost:5688",
        //     dtlscoap.NewDTLSClientOptions(piondtls.WithPSK(...), piondtls.WithCertificates(...)))

        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)
    }
DTLS Options-based API (pion/dtls v3)

Deprecation notice: *dtls.Config is deprecated in pion/dtls v3 in favour of immutable options-based configurations. Its use in go-coap is consequently deprecated as well and may be removed in a future major version. Migrate to net.NewDTLSServerOptions / dtls.NewDTLSClientOptions as shown below.

In addition to the legacy *dtls.Config, go-coap supports the options-based API introduced in pion/dtls v3. Both approaches are currently accepted by the same generic functions (ListenAndServeDTLS, Dial, NewDTLSListener).

Use net.NewDTLSServerOptions(...) / dtls.NewDTLSClientOptions(...) to compose DTLS configurations from individual options:

import (
    coap   "github.com/plgd-dev/go-coap/v3"
    coapnet "github.com/plgd-dev/go-coap/v3/net"
    coapdtls "github.com/plgd-dev/go-coap/v3/dtls"
    piondtls "github.com/pion/dtls/v3"
)

// Server
serverOpts := coapnet.NewDTLSServerOptions(
    piondtls.WithPSK(func(hint []byte) ([]byte, error) {
        return []byte{0xAB, 0xC1, 0x23}, nil
    }),
    piondtls.WithCipherSuites(piondtls.TLS_PSK_WITH_AES_128_CCM_8),
)
log.Fatal(coap.ListenAndServeDTLS("udp", ":5688", serverOpts, r))

// Client
clientOpts := coapdtls.NewDTLSClientOptions(
    piondtls.WithPSK(func(hint []byte) ([]byte, error) {
        return []byte{0xAB, 0xC1, 0x23}, nil
    }),
    piondtls.WithCipherSuites(piondtls.TLS_PSK_WITH_AES_128_CCM_8),
)
co, err := coapdtls.Dial("localhost:5688", clientOpts)

See examples/options/server/ and examples/options/client/ for complete working examples using the options-based API.

Observe / Notify

Server example.

Client example.

Multicast

Server example.

Client example.

License

Apache 2.0

FOSSA Status

Support go-coap

If go-coap is useful to you, you can buy us a coffee for $3 or choose another amount.

  • By card: Sponsor plgd-dev on GitHub and choose a one-time $3 sponsorship or enter a custom amount. This requires GitHub Sponsors to be enabled for the plgd-dev organization.

Documentation

Overview

Package coap provides a CoAP client and server.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ListenAndServe

func ListenAndServe(network string, addr string, handler mux.Handler) (err error)

ListenAndServe Starts a server on address and network specified Invoke handler for incoming queries.

func ListenAndServeDTLS

func ListenAndServeDTLS[T net.DTLSServerConfig](network string, addr string, cfg T, handler mux.Handler) (err error)

ListenAndServeDTLS starts a server on address and network over DTLS. cfg accepts either a *piondtls.Config (backward-compatible legacy path) or a net.DTLSServerOptions value built with net.NewDTLSServerOptions (recommended).

func ListenAndServeDTLSWithOptions added in v3.1.5

func ListenAndServeDTLSWithOptions[T net.DTLSServerConfig](network string, addr string, cfg T, opts ...dtlsServer.Option) (err error)

ListenAndServeDTLSWithOptions starts a server on address and network over DTLS with go-coap server options. cfg accepts either a *piondtls.Config (backward-compatible legacy path) or a net.DTLSServerOptions value built with net.NewDTLSServerOptions (recommended).

func ListenAndServeTCPTLS

func ListenAndServeTCPTLS(network, addr string, config *tls.Config, handler mux.Handler) (err error)

ListenAndServeTCPTLS Starts a server on address and network over TLS specified Invoke handler for incoming queries.

func ListenAndServeTCPTLSWithOptions added in v3.1.5

func ListenAndServeTCPTLSWithOptions(network, addr string, config *tls.Config, opts ...tcpServer.Option) (err error)

ListenAndServeTCPTLSWithOptions Starts a server on address and network over TLS specified Invoke options for incoming queries.

func ListenAndServeWithOptions added in v3.1.5

func ListenAndServeWithOptions(network, addr string, opts ...any) (err error)

ListenAndServeWithOption Starts a server on address and network specified Invoke options for incoming queries. The options is only support tcpServer.Option and udpServer.Option

Types

This section is empty.

Directories

Path Synopsis
examples
dtls/cid/client command
dtls/cid/server command
dtls/pki/client command
dtls/pki/server command
dtls/psk/client command
dtls/psk/server command
mcast/client command
mcast/server command
observe/client command
observe/server command
options/client command
options/server command
oscore/client command
oscore/server command
simple/client command
simple/server command
internal
handshake
Package handshake bounds concurrent server-side TLS and DTLS handshakes.
Package handshake bounds concurrent server-side TLS and DTLS handshakes.
net
blockwise/internal/blocks
Package blocks contains wire types shared by the legacy and Q-Block engines.
Package blocks contains wire types shared by the legacy and Q-Block engines.
blockwise/qblock
Package qblock implements RFC 9177 datagram transfers independently of the legacy RFC 7959 blockwise engine.
Package qblock implements RFC 9177 datagram transfers independently of the legacy RFC 7959 blockwise engine.
oscore
Package oscore contains transport-independent RFC 8613 security-context and message-protection support.
Package oscore contains transport-independent RFC 8613 security-context and message-protection support.
oscore/proxy
Package proxy provides a minimal opaque forwarder for OSCORE-protected CoAP requests.
Package proxy provides a minimal opaque forwarder for OSCORE-protected CoAP requests.
oscore/store
Package store provides file-backed OSCORE state stores.
Package store provides file-backed OSCORE state stores.
pkg
fn
tcp
test
net
Helper package for tests, must not be used in production code.
Helper package for tests, must not be used in production code.
udp

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL