-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (48 loc) · 1.82 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/gorilla/handlers"
)
// CORS middleware implementation
func enableCorsMiddleware(next http.Handler) http.Handler {
return handlers.CORS(
handlers.AllowedOrigins([]string{"*"}),
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE"}),
handlers.AllowedHeaders([]string{"Content-Type", "Authorization"}),
)(next)
}
func main() {
// Set up for the routes
myRouter := mux.NewRouter()
// Apply CORS middleware
myRouter.Use(enableCorsMiddleware)
// Add API version prefix to the routes
apiRouter := myRouter.PathPrefix("/v1").Subrouter()
// Initialize database
db, err := initializeDB()
if err != nil {
log.Fatal("Error connecting to the database: ", err)
}
defer db.Close()
// Initialize CryptoCurrency service with database connection
cryptoService := NewCryptoCurrencyService(db)
// Register API endpoints with handlers
apiRouter.HandleFunc("/cryptovote", cryptoService.GetAllCryptoCurrencies).Methods("GET")
apiRouter.HandleFunc("/cryptovote/{id:[0-9]+}", cryptoService.GetCryptoCurrencyByID).Methods("GET")
apiRouter.HandleFunc("/cryptovote", cryptoService.CreateCryptoCurrency).Methods("POST")
apiRouter.HandleFunc("/cryptovote/{id:[0-9]+}/upvote", cryptoService.UpVoteCryptoCurrency).Methods("PUT")
apiRouter.HandleFunc("/cryptovote/{id:[0-9]+}/downvote", cryptoService.DownVoteCryptoCurrency).Methods("PUT")
apiRouter.HandleFunc("/cryptovote/{id:[0-9]+}", cryptoService.DeleteCryptoCurrency).Methods("DELETE")
// Start the server
serverPort := os.Getenv("PORT")
if serverPort == "" {
serverPort = "8080" // Default port if not set in environment variable
}
serverAddress := fmt.Sprintf(":%s", serverPort)
log.Println("Server listening on", serverAddress)
log.Fatal(http.ListenAndServe(serverAddress, myRouter))
}