<commit_before>package main

import (
	"encoding/json"
	"log"
	"net/http"
	"strconv"

	"github.com/gorilla/mux"
)

// DriverLocation models response from LocationService
type DriverLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	UpdatedAt string  `json:"updated_at"`
}

// APIResponse models the response to know if a driver is active
type APIResponse struct {
	ID     int  `json:"id"`
	Zombie bool `json:"zombie"`
}

func main() {
	r := mux.NewRouter().StrictSlash(true)
	r.HandleFunc("/drivers/{id:[0-9]+}", ZombieDriverHandler).Methods("GET")
	http.Handle("/", r)
	log.Printf("Server started and listening on port %d.", 1338)
	log.Fatal(http.ListenAndServe(":1338", nil))
}

// ZombieDriverHandler handles a user's request to know if a driver is active
func ZombieDriverHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("\t%s",
		r.RequestURI)
	// Read route parameter
	vars := mux.Vars(r)
	param := vars["id"]
	driverID, err := strconv.Atoi(param)
	if err != nil {
		log.Printf("Received bad request with driver id %s.", param)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	locations, err := getDriverLocations(driverID)
	if err != nil {
		// TODO add circuit breaker system
		log.Printf("Could not retrieve driver's locations.")
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	isZombie := isDriverZombie(locations)

	result := APIResponse{ID: driverID, Zombie: isZombie}
	w.Header().Set("Content-Type", "application/json")
	response, err := json.Marshal(result)
	if err != nil {
		log.Printf("Could not json encode response.")
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(response)
	return
}

func getDriverLocations(id int) ([]*DriverLocation, error) {
	return []*DriverLocation{
		&DriverLocation{
			Latitude:  42,
			Longitude: 2.3,
			UpdatedAt: "2016-06-10T19:43:22.232Z",
		},
		&DriverLocation{
			Latitude:  42,
			Longitude: 2.3,
			UpdatedAt: "2016-06-10T19:43:22.232Z",
		},
	}, nil
}

func isDriverZombie(locations []*DriverLocation) bool {
	return false
}<commit_msg>Added circuit breaker for calling location service<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gorilla/mux"
	"github.com/rubyist/circuitbreaker"
)

var breaker = circuit.NewConsecutiveBreaker(5)

// DriverLocation models response from LocationService
type DriverLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	UpdatedAt string  `json:"updated_at"`
}

// APIResponse models the response to know if a driver is active
type APIResponse struct {
	ID     int  `json:"id"`
	Zombie bool `json:"zombie"`
}

func main() {
	r := mux.NewRouter().StrictSlash(true)
	r.HandleFunc("/drivers/{id:[0-9]+}", ZombieDriverHandler).Methods("GET")
	http.Handle("/", r)
	log.Printf("Server started and listening on port %d.", 1338)
	log.Fatal(http.ListenAndServe(":1338", nil))
}

// ZombieDriverHandler handles a user's request to know if a driver is active
func ZombieDriverHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("\t%s",
		r.RequestURI)
	// Read route parameter
	vars := mux.Vars(r)
	param := vars["id"]
	driverID, err := strconv.Atoi(param)
	if err != nil {
		log.Printf("Received bad request with driver id %s.", param)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	locationURL := fmt.Sprintf("http://localhost:1339/drivers/%d", driverID)
	locations, err := getDriverLocations(breaker, locationURL)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	isZombie := isDriverZombie(locations)

	result := APIResponse{ID: driverID, Zombie: isZombie}
	w.Header().Set("Content-Type", "application/json")
	response, err := json.Marshal(result)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(response)
	return
}

func getDriverLocations(breaker *circuit.Breaker, serviceURL string) ([]*DriverLocation, error) {
	// return []*DriverLocation{
	// 	&DriverLocation{
	// 		Latitude:  42,
	// 		Longitude: 2.3,
	// 		UpdatedAt: "2016-06-10T19:43:22.232Z",
	// 	},
	// 	&DriverLocation{
	// 		Latitude:  42,
	// 		Longitude: 2.3,
	// 		UpdatedAt: "2016-06-10T19:43:22.232Z",
	// 	},
	// }, nil
	var response *http.Response
	var err error
	err = breaker.Call(func() error {
		var httpErr error
		response, httpErr = http.Get(serviceURL)
		return httpErr
	}, time.Second*1)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	decoder := json.NewDecoder(response.Body)
	var locations []*DriverLocation
	if err := decoder.Decode(&locations); err != nil {
		return nil, err
	}
	return locations, nil
}

func isDriverZombie(locations []*DriverLocation) bool {
	return false
}
{'fraction_non_alphanumeric': 0.14321398834304747, 'fraction_numerical': 0.024562864279766863, 'mean_word_length': 4.362723214285714, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1097106', 'n_tokens_mistral': 1836, 'n_tokens_neox': 1698, 'n_words': 397}