package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("fm transfer"))
})
http.HandleFunc("/fm", handleFm)
_ = http.ListenAndServe(":80", nil)
}
func sendRequest(url string) (<-chan []byte,chan bool) {
dataChannel :=make(chan []byte, 10)
exitSignal:=make(chan bool)
go func() {
res, err := http.Get(url)
if err != nil {
return
}
defer res.Body.Close()
for {
select {
case <-exitSignal:
fmt.Println("sendRequest goroutine exit!")
return
default:{
buf := make([]byte, 4096)
n, err:= res.Body.Read(buf)
if err != nil || n == 0{
fmt.Println("recv data error!")
return
}else{
dataChannel<-buf[:n]
}
}
}
}
}()
return dataChannel,exitSignal
}
func sendResponse(w http.ResponseWriter,dataChannel <-chan []byte) {
for {
responseData,ok := <- dataChannel
if (!ok){
fmt.Println("read data error!")
break
}
n, err := w.Write(responseData)
if err != nil || n == 0 {
fmt.Println("send data error!")
break
}
}
}
func handleFm(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
url:=r.Form.Get("url")
w.Header().Set("Content-Type","audio/mpeg")
w.Header().Set("transfer-encoding","identity")
dataChannel,exitSignal:=sendRequest(url);
sendResponse(w,dataChannel)
exitSignal<-true
fmt.Println("handleFm finish!")
}
有疑问加站长微信联系(非本文作者)