coap

package module
v3.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 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

Requirements

  • Go 1.26 or higher

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.

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
simple/client command
simple/server command
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.
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