Skip to content

Instantly share code, notes, and snippets.

@lateefj
Created January 4, 2014 02:33
Show Gist options
  • Save lateefj/8250745 to your computer and use it in GitHub Desktop.
Save lateefj/8250745 to your computer and use it in GitHub Desktop.
Name search example code.
// Handlers for doing name searching
package names
import (
"encoding/json"
"fmt"
"net/http"
"github.com/golang/glog"
"github.com/gorilla/context"
"github.com/gorilla/mux"
)
// Taken from gorilla mux: https://github.com/gorilla/context/blob/master/context.go
// START
type contextKey int
const (
varsKey contextKey = iota
)
// END
// CensusName [...] Modal of the main data that is being searched
type CensusName struct {
Year int `json:"year"`
Name string `json:"name"`
Sex string `json:"sex"`
Size int `json:"size"`
}
// NameSearch [...] Interface that takes a string and return a bunch a list of CencusName
type NameSearch interface {
FindByName(string) (*[]CensusName, error)
}
// NameHandlerFunc [...] function type that defines a specific handler
type NameHandlerFunc func(NameSearch, http.ResponseWriter, *http.Request)
// NameResponse [...] structure for returning to the client
type NameResponse struct {
Male []CensusName `json:"male"`
Female []CensusName `json:"female"`
}
// Finds a name based on the string and optional sex of the
func handleFindName(nm NameSearch, w http.ResponseWriter, r *http.Request) {
//vars := mux.Vars(r)
vars := context.Get(r, varsKey).(map[string]string)
// No name then error out no searching
name, ok := vars["name"]
if !ok {
glog.Error("Error could not find name variable")
http.Error(w, "Didn't specify a name!", http.StatusInternalServerError)
return
}
// Response
var cns *[]CensusName
var err error
// Call the namesearch search function
cns, err = nm.FindByName(name)
// Errors happen ;(
if err != nil {
glog.Error("Error doing name asearch %s", err)
http.Error(w, fmt.Sprintf("Error searching for name: %s", err), http.StatusInternalServerError)
return
}
/// Build response
nresp := NameResponse{Male: make([]CensusName, 0), Female: make([]CensusName, 0)}
for _, c := range *cns {
if c.Sex == "M" {
nresp.Male = append(nresp.Male, c)
} else {
nresp.Female = append(nresp.Female, c)
}
}
b, err := json.Marshal(nresp)
if err != nil {
glog.Error("Error json marshaling %s", err)
http.Error(w, fmt.Sprintf("Couldn't marhal json: %s", err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(b)
}
// InitRest ... Simple sets up all the routes
func InitRest(r *mux.Router) {
sr := r.PathPrefix("/n/").Subrouter()
// NameSearchWrap provides the database connected NameSearch
sr.HandleFunc("/name/{name}", NameSearchWrap(handleFindName))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment