Skip to content

Instantly share code, notes, and snippets.

@johannes-riecken
Created November 26, 2018 21:13
Show Gist options
  • Save johannes-riecken/b8c7c0f4055a170cff9b0ffc187b449a to your computer and use it in GitHub Desktop.
Save johannes-riecken/b8c7c0f4055a170cff9b0ffc187b449a to your computer and use it in GitHub Desktop.
Partial implementation of github trending RESTful API
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
)
type Repository struct {
ID string `json:"id,omitempty"`
stars int `json:"stars,omitempty"`
forks int `json:"forks,omitempty"`
}
var trendingRepos []Repository
// Display all trending repositories. TODO: Add parameters for filter "s" and maximum number of results "limit"
func GetTrending(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(trendingRepos)
}
func main() {
router := mux.NewRouter()
// TODO: Replace with scraping code to get data from github. Maybe github also returns these data as JSON. I could find that out with the Firefox Web Developer Tools.
trendingRepos = append(trendingRepos, Repository{ID: "microsoft/dotnetreferencesource", stars: 100, forks: 123})
trendingRepos = append(trendingRepos, Repository{ID: "llvm/clang", stars: 321, forks: 57})
trendingRepos = append(trendingRepos, Repository{ID: "microsoft/code", stars: 999, forks: 666})
router.HandleFunc("/trending", GetTrending).Methods("GET")
// TODO: Add something like router.HandleFunc(...).Methods("GET").Queries("s", "{filterString}") to pass filterString to GetTrending function, ditto for limit parameter.
// Limit parameter can probably be specified as regex [0-9]+, which only allows positive integers. I don't think the server needs any additional error handling, although the scraper would need error handling (timeout, log message for connection failure or for invalid data from github, etc.)
log.Fatal(http.ListenAndServe(":8000", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment