// CreateUser creates a new user resource func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) { // Stub an user to be populated from the body u := models.User{} // Populate the user data json.NewDecoder(r.Body).Decode(&u) // Add an Id u.Id = bson.NewObjectId() // Write the user to mongo uc.session.DB("go_rest_tutorial").C("users").Insert(u) // Marshal provided interface into JSON structure uj, _ := json.Marshal(u) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(201) fmt.Fprintf(w, "%s", uj) }
func SetRoute(m *martini.ClassicMartini) { //主页 m.Get("/", func() string { return "<b>欢迎使用任务跟踪管理系统 version 0.1<b>" }) m.Get("/json", func() []byte { result, _ := json.Marshal("欢迎使用任务跟踪管理系统 version 0.1") return result }) m.Get("/task/json", func() []byte { output, _ := json.MarshalIndent(taskList, " ", " ") return output }) m.Get("/task/json/:id", func(params martini.Params) []byte { id, _ := strconv.Atoi(params["id"]) if len(taskList.List) > id { one := taskList.List[id] output, _ := json.MarshalIndent(one, " ", " ") return output } else { return []byte("<Task><Content>task not found.</Content></Task>") } }) //所有任务 m.Get("/task/all", func() string { return taskList.String() }) m.Get("/task/xml", func() []byte { output, _ := xml.MarshalIndent(taskList, " ", " ") return output }) m.Get("/task/xml/:id", func(params martini.Params) []byte { id, _ := strconv.Atoi(params["id"]) if len(taskList.List) > id { one := taskList.List[id] output, _ := xml.MarshalIndent(one, " ", " ") return output } else { return []byte("<Task><Content>task not found.</Content></Task>") } }) //单个任务 m.Get("/task/:id", func(params martini.Params) string { id, _ := strconv.Atoi(params["id"]) if len(taskList.List) > id { one := taskList.List[id] return one.String() } else { return "<b>task not found.<b>" } }) //用户登录 m.Get("/hello/:name", func(params martini.Params) string { var u models.User u.Id = 999 u.Name = params["name"] fmt.Println(u) return "Hello " + params["name"] }) }