コード例 #1
0
ファイル: topics_api.go プロジェクト: mssola/todo
// TopicsUpdateJSON responds to: PUT/PATCH /topics/:id. This will only be
// called when the user requested a JSON response.
func TopicsUpdateJSON(res http.ResponseWriter, req *http.Request) {
	var str, value string
	var p *params

	if p = getFromBody(req); p == nil {
		lib.JSONError(res)
		return
	}

	// Execute the update query. Depending on the given parameters this will be
	// just a plain rename, or a full update.
	if value = p.Name; value == "" {
		str = "contents"
		if value = p.Contents; value == "" {
			lib.JSONError(res)
			return
		}
	} else {
		str = "name"
	}

	// And finally send the JSON response.
	var t Topic
	str = fmt.Sprintf("update topics set %v=$1 where id=$2 returning *", str)
	err := Db.SelectOne(&t, str, value, mux.Vars(req)["id"])
	renderJSON(res, &t, err, true)
}
コード例 #2
0
ファイル: topics_api.go プロジェクト: mssola/todo
// TopicsCreateJSON responds to: POST /topics. This will only be called when
// the user requested a JSON response.
func TopicsCreateJSON(res http.ResponseWriter, req *http.Request) {
	if p := getFromBody(req); p == nil {
		lib.JSONError(res)
	} else {
		t, err := createTopic(p.Name)
		renderJSON(res, t, err, false)
	}
}
コード例 #3
0
ファイル: topics_api.go プロジェクト: mssola/todo
// Safely render and send a JSON response with the given topic. This function
// should be called after performing some operation that might return an error.
// This error from the previous operation is the third parameter. The fourth
// parameter tells this function to generate the Markdown code for this topic.
func renderJSON(res http.ResponseWriter, topic *Topic, err error, md bool) {
	// Try to render the given Topic.
	if err == nil {
		if md {
			topic.RenderMarkdown()
		}
		if b, err := json.Marshal(topic); err == nil {
			fmt.Fprint(res, string(b))
			res.Header().Set("Content-Type", "application/json")
			return
		}
	}

	// Render a generic error.
	lib.JSONError(res)
}