Created
September 22, 2020 16:36
-
-
Save beriberikix/396c4570086ebbfa8d1e3b5c97945d69 to your computer and use it in GitHub Desktop.
go-coap client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"os" | |
"time" | |
"github.com/plgd-dev/go-coap/v2/udp" | |
) | |
func main() { | |
co, err := udp.Dial("localhost:5683") | |
if err != nil { | |
log.Fatalf("Error dialing: %v", err) | |
} | |
path := "/a" | |
if len(os.Args) > 1 { | |
path = os.Args[1] | |
} | |
ctx, cancel := context.WithTimeout(context.Background(), time.Second) | |
defer cancel() | |
resp, err := co.Get(ctx, path) | |
if err != nil { | |
log.Fatalf("Error sending request: %v", err) | |
} | |
log.Printf("Response payload: %v", resp.String()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"log" | |
coap "github.com/plgd-dev/go-coap/v2" | |
"github.com/plgd-dev/go-coap/v2/message" | |
"github.com/plgd-dev/go-coap/v2/message/codes" | |
"github.com/plgd-dev/go-coap/v2/mux" | |
) | |
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) | |
} | |
} | |
func main() { | |
r := mux.NewRouter() | |
r.Handle("/a", mux.HandlerFunc(handleA)) | |
log.Fatal(coap.ListenAndServe("udp", ":5683", r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment