Select Git revision
handlers.go
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
handlers.go 3.79 KiB
package handlers
import (
"encoding/json"
"net/http"
"assignment1/models"
"assignment1/services"
"fmt"
)
// BookCountHandler handles requests to the /librarystats/v1/bookcount/ endpoint.
func BookCountHandler(w http.ResponseWriter, r *http.Request) {
// Extract query parameters for language
query := r.URL.Query()
language := query.Get("language")
// Fetch book data from the Gutendex API
booksResponse, err := services.FetchBooksByLanguage(language)
if err != nil {
http.Error(w, "Failed to fetch books: "+err.Error(), http.StatusInternalServerError)
return
}
// Process the books to calculate the book count and author count
bookCount := len(booksResponse.Results)
authorCount := services.CalculateUniqueAuthors(booksResponse.Results)
// Create a response object
response := map[string]interface{}{
"language": language,
"bookCount": bookCount,
"authorCount": authorCount,
}
// Write the response back as JSON
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to encode response: "+err.Error(), http.StatusInternalServerError)
}
}
func ReadershipHandler(w http.ResponseWriter, r *http.Request) {
// Extract the language code from the URL path
language := r.URL.Path[len("/librarystats/v1/readership/"):]
// Optional: Parse query parameters for limit if present
query := r.URL.Query()
limitParam := query.Get("limit")
var limit int
if limitParam != "" {
fmt.Sscanf(limitParam, "%d", &limit)
}
// Fetch book data from the Gutendex API
books, err := services.FetchBooksByLanguage(language)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Fetch countries for the given language
countries, err := services.FetchCountriesByLanguage(language)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Fetch population data for each country and calculate total readership
var readershipDetails []models.ReadershipDetail
var totalReadership int64 = 0
for _, country := range countries { // Directly range over countries
population, err := services.FetchPopulationByCountryCode(country.ISOCode)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
totalReadership += population
readershipDetail := models.ReadershipDetail{
Country: country.Official_Name,
ISOCode: country.ISO3166_1_Alpha_2, // Corrected field access
Books: len(books.Results),
Authors: services.CalculateUniqueAuthors(books.Results),
Readership: population,
}
readershipDetails = append(readershipDetails, readershipDetail)
// Apply limit if specified
if limit > 0 && len(readershipDetails) >= limit {
break
}
}
// Create and send the response
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(readershipDetails)
}
func StatusHandler(w http.ResponseWriter, r *http.Request) {
status := models.ServiceStatus{
GutendexAPI: services.CheckServiceAvailability("http://129.241.150.113:8000/books/"),
LanguageAPI: services.CheckServiceAvailability("http://129.241.150.113:3000/language2countries/"),
CountriesAPI: services.CheckServiceAvailability("http://129.241.150.113:8080/v3.1/"),
Version: "v1",
Uptime: services.GetUptime(), // Implement GetUptime in services package
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(status)
}