-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
62 lines (52 loc) · 1.46 KB
/
Copy pathmain.go
File metadata and controls
62 lines (52 loc) · 1.46 KB
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
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"github.com/juju/ratelimit"
httpSwagger "github.com/swaggo/http-swagger"
"log"
"net/http"
"os"
"weather-api/config"
_ "weather-api/docs"
"weather-api/models"
"weather-api/routes"
)
func init() {
if err := godotenv.Load(); err != nil {
log.Fatal("Error loading .env file")
}
}
func main() {
mongoURI := os.Getenv("MONGODB_URI")
apiKey := os.Getenv("WEATHERSTACK_API_KEY")
if mongoURI == "" || apiKey == "" {
log.Fatal("MONGODB_URI veya WEATHERSTACK_API_KEY tanımlı değil.")
}
config.ConnectMongoDB(mongoURI)
defer config.CloseMongoDB()
err := models.CreateTTLIndex(config.Client)
if err != nil {
log.Fatalf("TTL indeksi oluşturulamadı: %v", err)
}
r := mux.NewRouter()
r.HandleFunc("/weather/{city}", routes.GetWeather(apiKey)).Methods("GET")
r.HandleFunc("/weather", routes.CreateWeather).Methods("POST")
r.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)
bucket := ratelimit.NewBucketWithRate(1, 5)
r.Use(RateLimiter(bucket))
fmt.Println("API calisiyor...")
log.Fatal(http.ListenAndServe(":8080", r))
}
func RateLimiter(bucket *ratelimit.Bucket) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if bucket.TakeAvailable(1) == 0 {
http.Error(w, "Too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
}