Skip to content

Instantly share code, notes, and snippets.

@jantore
Created November 3, 2014 19:00
Show Gist options
  • Save jantore/818497ae1ce5ef92977e to your computer and use it in GitHub Desktop.
Save jantore/818497ae1ce5ef92977e to your computer and use it in GitHub Desktop.
Multicast to HTTP in Go
package main
import (
"log"
"net"
"net/http"
"regexp"
"io"
"strconv"
)
func handle_request(w http.ResponseWriter, r *http.Request) {
re := regexp.MustCompile(`^/(\d+\.\d+\.\d+\.\d+)/(\d+)(?:/.*)$`)
m := re.FindStringSubmatch(r.URL.Path)
if m == nil {
log.Print("did not match")
http.NotFound(w, r)
return
}
addr := net.ParseIP(m[1])
if addr == nil {
log.Print("invalid IP address")
http.NotFound(w, r)
return
}
port, err := strconv.Atoi(m[2])
if err != nil || port < 0 || port > 65535 {
log.Print(err)
http.NotFound(w, r)
return
}
conn, err := net.ListenMulticastUDP("udp", nil, &net.UDPAddr{
addr,
port,
})
if err != nil {
log.Printf("could not create UDP socket: %s", err)
conn.Close()
return
}
w.Header().Set("Content-Type", "application/octet-stream")
io.Copy(w, conn)
conn.Close()
}
func main() {
http.HandleFunc("/", handle_request)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment