github.com/l3x/learn-fp-go@v0.0.0-20171228022418-7639825d0b71/1-functional-fundamentals/ch03-hof/03_hof/src/hof/restful.go (about) 1 package hof 2 3 import ( 4 "fmt" 5 "github.com/julienschmidt/httprouter" 6 "net/http" 7 "encoding/json" 8 "log" 9 "strconv" 10 ) 11 12 func CarsIndexHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 13 response, err := getAllCarsJson() 14 if err != nil { 15 panic(err) 16 } 17 w.Header().Set("Content-Type", "application/json") 18 fmt.Fprintf(w , string(response)) 19 } 20 21 func CarHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 22 carIndex, err := strconv.Atoi(p[0].Value) 23 if err != nil { 24 log.Fatal("CarHandler unable to find car (%v) by index\n", p[0].Value) 25 } 26 response, err := getThisCarJson(carIndex) 27 if err != nil { 28 panic(err) 29 } 30 w.Header().Set("Content-Type", "application/json") 31 fmt.Fprintf(w , string(response)) 32 } 33 34 func getAllCarsJson() ([]byte, error) { 35 return json.MarshalIndent(Payload{CarsDB}, "", " ") 36 } 37 38 func getThisCarJson(carIndex int) ([]byte, error) { 39 return json.MarshalIndent(CarsDB[carIndex], "", " ") 40 } 41 42 func GetThisCar(carIndex int) (*IndexedCar, error) { 43 44 thisCarJson, err := getThisCarJson(carIndex) 45 if err != nil { 46 panic(err) 47 } 48 49 // Decode the json into our struct type. 50 // We don't need to check for errors, the caller can do this. 51 52 var thisIndexedCar IndexedCar 53 if err := json.Unmarshal(thisCarJson, &thisIndexedCar); err != nil { 54 panic(err) 55 } 56 //log.Printf("carIndex: %v\n", carIndex) 57 //log.Printf("thisCarJson: %v\n", thisCarJson) 58 //log.Printf("thisIndexedCar: %v\n", thisIndexedCar) 59 return &thisIndexedCar, err 60 }