Last active
November 5, 2017 18:19
-
-
Save nmeum/720449d17086b4003de4c7f70370e62f to your computer and use it in GitHub Desktop.
CoAP server writting payloads to a file
This file contains 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 ( | |
"flag" | |
"github.com/dustin/go-coap" | |
"log" | |
"net" | |
"os" | |
"path/filepath" | |
) | |
var ( | |
addr = flag.String("addr", ":5683", "Address the server should listen on") | |
ntype = flag.String("ntype", "udp", "Network type to use") | |
) | |
var cmap map[uint16]bool | |
type FileServer struct { | |
file *os.File | |
} | |
func errMsg(m *coap.Message, code coap.COAPCode) *coap.Message { | |
var res coap.Message | |
res.MessageID = m.MessageID | |
if m.IsConfirmable() { | |
res.Type = coap.Acknowledgement | |
res.Token = m.Token | |
} | |
res.Code = code | |
return &res | |
} | |
func (fs FileServer) ServeCOAP(c *net.UDPConn, a *net.UDPAddr, m *coap.Message) *coap.Message { | |
log.Printf("Got message in ServeCOAP: path=%q: %#v from %v", m.Path(), m, a) | |
if val, ok := cmap[m.MessageID]; ok && val { | |
return nil | |
} | |
if m.Code == coap.POST && m.IsConfirmable() { | |
_, err := fs.file.Write(m.Payload) | |
if err != nil { | |
return errMsg(m, coap.InternalServerError) | |
} | |
res := &coap.Message{ | |
Type: coap.Acknowledgement, | |
Code: coap.Content, | |
MessageID: m.MessageID, | |
Token: m.Token, | |
} | |
cmap[m.MessageID] = true | |
return res | |
} | |
return errMsg(m, coap.BadRequest) | |
} | |
func main() { | |
flag.Parse() | |
args := flag.Args() | |
if len(args) < 1 { | |
os.Exit(1) | |
} | |
file, err := os.OpenFile(args[0], os.O_APPEND|os.O_WRONLY, 0644) | |
if err != nil { | |
panic(err) | |
} | |
defer file.Close() | |
fs := FileServer{file} | |
mux := coap.NewServeMux() | |
mux.Handle("/"+filepath.Base(args[0]), fs) | |
cmap = make(map[uint16]bool) | |
log.Fatal(coap.ListenAndServe(*ntype, *addr, mux)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment