This repository has been archived by the owner on Mar 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
154 lines (121 loc) · 3.53 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"github.com/solairerove/linden-honey-go/model"
"html"
"log"
"net/http"
"os"
"strconv"
)
const (
lindenHoneyScraperURL = "LINDEN_HONEY_SCRAPER_URL"
usingLindenHoneyScraper = "USING_LINDEN_HONEY_SCRAPER"
postgresHost = "POSTGRES_HOST"
// TODO: to .env
dbUsername = "linden-honey-user"
dbPassword = "linden-honey-pass"
dbName = "linden-honey"
)
type Server struct {
db *sql.DB
}
func main() {
log.Println("Starting application")
// load env
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env file", err)
}
server := Server{}
dbHost := fmt.Sprintf("%s", os.Getenv(postgresHost))
connectionString := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
dbHost, dbUsername, dbPassword, dbName, "5432")
server.db, err = sql.Open("postgres", connectionString)
if err != nil {
log.Fatal(err)
}
// get scraper bool from .env file
useScrapper, err := strconv.ParseBool(os.Getenv(usingLindenHoneyScraper))
if err != nil {
log.Fatal("Can't parse to bool value: ", err)
}
log.Println(usingLindenHoneyScraper, useScrapper)
scraperURL := fmt.Sprintf("%s/songs", os.Getenv(lindenHoneyScraperURL))
log.Println(lindenHoneyScraperURL, scraperURL)
// TODO: rewrite and move to package after go web udemy
// fetch and update collection if necessary
if useScrapper {
resp, err := http.Get(scraperURL)
if err != nil {
log.Fatal("Error loading data from scraper: ", err)
}
defer func() {
err := resp.Body.Close()
if err != nil {
log.Fatal("Error closing body from scraper: ", err)
}
}()
songs := make([]model.Song, 0)
err = json.NewDecoder(resp.Body).Decode(&songs)
if err != nil {
log.Fatal("Error unmarshalling data from scraper: ", err)
}
for _, s := range songs {
s.SaveSong(server.db)
}
}
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", index).Methods("GET")
router.HandleFunc("/songs/{id}", server.getSongByID).Methods("GET")
router.HandleFunc("/songs", server.getSongByName).Methods("GET")
// change on local dev if needed
log.Fatal(http.ListenAndServe(":8080", handlers.CompressHandler(router)))
}
func index(w http.ResponseWriter, r *http.Request) {
_, err := fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
if err != nil {
log.Fatalf("Something wrong with greeting endppoint: %v", err)
}
}
func (s *Server) getSongByID(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
song, err := model.FindSongByID(s.db, id)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, song)
}
func (s *Server) getSongByName(w http.ResponseWriter, r *http.Request) {
vals := r.URL.Query()
names, ok := vals["name"]
var name string
if ok {
if len(names) >= 1 {
name = names[0]
}
}
songsMap, err := model.FetchNameToIDMapByName(s.db, name)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, songsMap)
}
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}