Skip to content

Instantly share code, notes, and snippets.

@dkua
Last active August 29, 2015 13:57
Show Gist options
  • Save dkua/9460748 to your computer and use it in GitHub Desktop.
Save dkua/9460748 to your computer and use it in GitHub Desktop.
Go program for finding out the average number of students per section from the Clever API.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Response struct {
Paging struct {
Count float64
}
Data []SectionData
}
type SectionData struct {
Data struct {
Students []string
}
}
func main() {
// Setup request to get all Sections from Clever API.
// Set limit to 1000 so only need to read one page.
req, err := http.NewRequest("GET", "https://api.clever.com/v1.1/sections?limit=1000", nil)
if err != nil {
fmt.Println("Error:", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
req.SetBasicAuth("DEMO_KEY", "")
// Make request to Clever API and unmarshall the response into the structs above.
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error:", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
}
response := &Response{}
json.Unmarshal(body, &response)
// Sum up students and calculate the average number of students per section.
totalStudents := 0.0
totalSections := response.Paging.Count
for _, section := range response.Data {
totalStudents += float64(len(section.Data.Students))
}
fmt.Println("Total Students:", totalStudents)
fmt.Println("Total Sections:", totalSections)
fmt.Println("Average Number of Students per Section:", totalStudents/totalSections)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment