Skip to content

Instantly share code, notes, and snippets.

@dewey4iv
Created February 9, 2018 07:01
Show Gist options
  • Save dewey4iv/c017ea69fbf6a62782c294a0c9f57527 to your computer and use it in GitHub Desktop.
Save dewey4iv/c017ea69fbf6a62782c294a0c9f57527 to your computer and use it in GitHub Desktop.
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