-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
93 lines (69 loc) · 1.52 KB
/
main.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"runtime"
gotdotenv "github.com/joho/godotenv"
"github.com/javokhirbek1999/tez-spider/handlers"
)
type Response struct {
Data []handlers.Song
Total int64
StatusCode int
}
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func enableCORS(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}
func main() {
if err := gotdotenv.Load(".env"); err != nil {
log.Fatalln("Couldn't load environment variables")
return
}
port := os.Getenv("PORT")
if port == "" {
port = "4000"
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
enableCORS(&w)
fmt.Fprintf(w, "Welcome")
})
http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
enableCORS(&w)
query := r.URL.Query().Get("query")
songs := handlers.Crawler(query)
encoder := json.NewEncoder(w)
totalSongs := len(songs)
if totalSongs == 0 {
encoder.Encode(Response{
Data: nil,
Total: 0,
StatusCode: http.StatusBadRequest,
})
} else {
encoder.Encode(Response{
Data: songs,
Total: int64(totalSongs),
StatusCode: http.StatusOK,
})
}
})
go func() {
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Fatalf("Server Error: %v", err)
return
}
}()
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt)
signal.Notify(sig, os.Kill)
signalMessage := <-sig
log.Fatalf("Server stopped: %v\n", signalMessage)
}