Created
February 9, 2018 07:01
-
-
Save dewey4iv/c017ea69fbf6a62782c294a0c9f57527 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
var f finder | |
func findCountry(w http.ResponseWriter, r *http.Request) { | |
params := mux.Vars(r) | |
country, err := f.FindByName(params["id"]) | |
if err != nil { | |
http.Error(w, "Invalid Country", http.StatusNotFound) | |
log.Printf("unable to find country with name: %s", params["id"]) | |
return | |
} | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(http.StatusFound) | |
if err := json.NewEncoder(w).Encode(country); err != nil { | |
log.Printf("error encoding: %v", err) | |
} | |
} | |
func main() { | |
r := mux.NewRouter() | |
r.PathPrefix("/").Handler(http.FileServer(http.Dir("site"))) | |
r.HandleFunc("/country/{id}", findCountry).Methods("GET") | |
if err := http.ListenAndServe(":3000", r); err != nil { | |
log.Fatal(err) | |
} | |
} | |
type finder interface { | |
FindByName(string) (interface{}, error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment