47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
|
err := json.NewDecoder(r.Body).Decode(&reqItem)
|
|
if err != nil {
|
|
return err
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func InvalidJson(err error) string {
|
|
return fmt.Sprintf("Invalid JSON: %s", err.Error())
|
|
}
|
|
|
|
// Helper function to send JSON responses
|
|
// TODO: Change type of data to any
|
|
func RespondWithJSON(w http.ResponseWriter, statusCode int, data interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(statusCode)
|
|
if err := json.NewEncoder(w).Encode(data); err != nil {
|
|
log.Printf("Error encoding JSON: %v", err)
|
|
}
|
|
}
|
|
|
|
// Gets the query parameter from the URL
|
|
func ParseQueryParams(r *http.Request, query string) (*string, error) {
|
|
queryParams := r.URL.Query()
|
|
if _, exists := queryParams[query]; exists {
|
|
value := queryParams.Get(query)
|
|
if len(value) == 0 {
|
|
return nil, fmt.Errorf("Value of query parameter is empty")
|
|
} else {
|
|
return &value, nil
|
|
}
|
|
} else {
|
|
return nil, fmt.Errorf("Could not find query %s", query)
|
|
}
|
|
}
|