Skip to content

Instantly share code, notes, and snippets.

@karansinghgit
Created June 9, 2020 13:41
Show Gist options
  • Save karansinghgit/256a3f69698004cab4024c39767a0be1 to your computer and use it in GitHub Desktop.
Save karansinghgit/256a3f69698004cab4024c39767a0be1 to your computer and use it in GitHub Desktop.
Creating an API using mux: How can I refactor this code?
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/google/go-github/v31/github"
"github.com/gorilla/mux"
"golang.org/x/oauth2"
)
var client *github.Client
var ctx context.Context
type Repository struct {
Owner string `json:"owner"`
Name string `json:"name"`
}
type Frequency struct {
Date string `json:"date"`
Count int `json:"count"`
}
var currentRepository = Repository{
Owner: "randomusername",
Name: "foobar",
}
const GITHUB_AUTH_TOKEN string = "MY_AUTH_TOKEN"
func init() {
ctx = context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: GITHUB_AUTH_TOKEN},
)
tc := oauth2.NewClient(ctx, ts)
client = github.NewClient(tc)
}
func parseURL(repoURL *string) Repository {
res := currentRepository
if *repoURL != "" {
index := strings.Index(*repoURL, "github.com")
repo := *repoURL
repo = repo[index+11:]
var base []string
base = strings.Split(repo, "/")
var ans []string
for _, e := range base {
if e != "" {
ans = append(ans, e)
}
}
res = Repository{
Owner: ans[0],
Name: ans[1],
}
}
return res
}
func getCommitTimeStamps(repo Repository) []time.Time {
var commitTimeStamps []time.Time
opt := &github.CommitsListOptions{
ListOptions: github.ListOptions{PerPage: 50},
}
var allRepositoryCommits []*github.RepositoryCommit
for {
repositoryCommits, resp, err := client.Repositories.ListCommits(ctx, repo.Owner, repo.Name, opt)
if err != nil {
fmt.Println(err)
}
allRepositoryCommits = append(allRepositoryCommits, repositoryCommits...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
for _, e := range allRepositoryCommits {
commitTimeStamps = append(commitTimeStamps, *e.GetCommit().Author.Date)
}
return commitTimeStamps
}
func parseTimeStamps(commitTimeStamps []time.Time) []Frequency {
const RFC3339FullDate = "2006-08-06"
timeSeries := make([]string, len(commitTimeStamps))
for i, t := range commitTimeStamps {
timeSeries[i] = fmt.Sprintf("%d-%02d-%02d", t.Year(), t.Month(), t.Day())
}
m := make(map[string]int)
for _, t := range timeSeries {
m[t]++
}
var f []Frequency
for k, v := range m {
f = append(f, Frequency{
Date: k,
Count: v,
})
}
return f
}
func getHome(w http.ResponseWriter, r *http.Request) {
commitTimeStamps := getCommitTimeStamps(currentRepository)
commitTimeObjects := parseTimeStamps(commitTimeStamps)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
_ = json.NewEncoder(w).Encode(commitTimeObjects)
}
func updateRepository(w http.ResponseWriter, r *http.Request) {
var url struct {
URL string `json:"url"`
}
_ = json.NewDecoder(r.Body).Decode(&url)
currentRepository = parseURL(&url.URL)
fmt.Println(currentRepository)
// currentRepository looks like {bradtraversy reactcharts}
commitTimeStamps := getCommitTimeStamps(currentRepository)
commitTimeObjects := parseTimeStamps(commitTimeStamps)
// commitTimeObjects looks like [{2016-04-21 2} {2016-04-23 5} {2016-04-25 1}]
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "PUT")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
fmt.Println(currentRepository)
_ = json.NewEncoder(w).Encode(commitTimeObjects)
}
func main() {
router := mux.NewRouter()
router.Use(mux.CORSMethodMiddleware(router))
router.HandleFunc("/", getHome).Methods("GET", "OPTIONS")
router.HandleFunc("/updateRepository", updateRepository).Methods("PUT", "OPTIONS")
http.ListenAndServe(":8000", router)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment