- Learning Functional Programming in Go
- Lex Sheehan
- 346字
- 2021-07-02 23:13:40
More application code
The first thing we do in the main() function is check the RUN_HTTP_SERVER environment variable. If it's set to true, then the program will set up two routes. The first route /cars returns the index page that displays all the cars that have been loaded from the .csv files. The second route /cars/:id retrieves an inpidual car object and returns its JSON representation:
func main() {
if os.Getenv("RUN_HTTP_SERVER") == "TRUE" {
router := httprouter.New()
router.GET("/cars", CarsIndexHandler)
router.GET("/cars/:id", CarHandler)
log.Println("Listening on port 8000")
log.Fatal(http.ListenAndServe(":8000", router))
The IndexedCars variable is defined in types.go as follows:
IndexedCar struct {
Index int `json:"index"`
Car string` json:"car"`
}
Before we look at the else logic, let's take a peek at the following cars.go file. We declare an exported package level variable CarsDB that is assigned a slice of IndexedCars:
package hof
import (
"fmt"
s "strings"
"regexp"
"log"
"encoding/json"
)
var CarsDB = initCarsDB()
func initCarsDB() []IndexedCar {
var indexedCars []IndexedCar
for i, car := range LoadCars() {
indexedCars = append(indexedCars, IndexedCar{i, car})
}
lenCars := len(indexedCars)
for i, car := range LoadMoreCars() {
indexedCars = append(indexedCars, IndexedCar{i + lenCars, car})
}
return indexedCars
}
func LoadCars() Collection {
return CsvToStruct("cars.csv")
}
Note that every Go source file in our 01_hof directory uses the package name hof.
We preface the strings package with s so that we can easily reference string utility functions with s like this: s.Contains(car, make) rather than strings.Contains(car, make).
Since var CarsDB = initCarsDB() is defined at the package level, it will be evaluated when we start our chapter4 executable. The initCarsDB() function only needs to be referenced in this cars.go file, so we do not need to capitalize its first character.
The LoadCars() function, on the other hand, is referenced by the main package, so we need to capitalize its first character in order to make it accessible.
Now, let's turn our attention to the FP goodies in the else block.