-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.go
52 lines (43 loc) · 1.08 KB
/
http_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
func makeHandleVideoUrlPost(videoUrls chan string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
bytes, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Error().Err(err).Msg("failed to read request body")
return
}
url := string(bytes)
videoUrls <- url
w.WriteHeader(http.StatusOK)
}
}
func listenHttp(port int, videoUrls chan string) {
handleVideoUrlPost := makeHandleVideoUrlPost(videoUrls)
r := mux.NewRouter()
r.HandleFunc("/download", handleVideoUrlPost).Methods("POST")
http.Handle("/", r)
addr := getListenAddr(port)
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal().Err(err).Send()
}
log.Info().Msgf("http server listening at %s", addr)
if err := http.Serve(l, nil); err != nil {
log.Fatal().Err(err).Send()
}
}
func getListenAddr(port int) string {
if isDevelopment() {
return fmt.Sprintf("localhost:%d", port)
} else {
return fmt.Sprintf(":%d", port)
}
}