Created
February 21, 2019 22:08
-
-
Save santiago/03be1ecb1a2d4db5bcb1799908b709f7 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
mux := http.NewServeMux() | |
mux.HandleFunc("/projects/", project.Project(session)) | |
func Project(session *mgo.Session) func(w http.ResponseWriter, req *http.Request) { | |
return func(w http.ResponseWriter, req *http.Request) { | |
middleware.DebugLogger.Println("Inside project controller") | |
switch req.Method { | |
case "GET": | |
handleGet(session, w, req) | |
case "POST": | |
handlePost(session, w, req) | |
case "PUT": | |
handlePut(session, w, req) | |
case "DELETE": | |
handleDelete(session, w, req) | |
} | |
} | |
} | |
func handlePost(session *mgo.Session, w http.ResponseWriter, req *http.Request) { | |
middleware.DebugLogger.Println("Inside the POST responder") | |
bodyJSONByte, _ := ioutil.ReadAll(req.Body) | |
var unmarshaledProject project.Project | |
err := project.Unmarshal(bodyJSONByte, &unmarshaledProject) | |
if err != nil { | |
middleware.ErrorLogger.Println(err) | |
b, _ := json.Marshal(map[string]interface{}{"message": "Could not read Projects from request", "code": http.StatusBadRequest}) | |
io.WriteString(w, string(b)) | |
return | |
} | |
Project := session.DB(config.DatabaseName).C(project.ProjectCollection) | |
middleware.DebugLogger.Println("Inserting project into database") | |
middleware.DebugLogger.Println(unmarshaledProject) | |
err = Project.Insert(unmarshaledProject) | |
if err != nil { | |
middleware.ErrorLogger.Println(err) | |
b, _ := json.Marshal(map[string]interface{}{"message": "Could not create Projects in database", "code": http.StatusInternalServerError}) | |
io.WriteString(w, string(b)) | |
return | |
} | |
b, _ := json.Marshal(map[string]interface{}{"projects": unmarshaledProject, "code": http.StatusOK}) | |
io.WriteString(w, string(b)) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment