Beispiel #1
0
Datei: api.go Projekt: w01/sac1
// Handle requests to /reset
func handleReset(w http.ResponseWriter, req *http.Request) *apiutil.Error {
	switch req.Method {

	case "GET":
		if req.URL.Path != "/reset" && req.URL.Path != "/reset/" {
			return errorInvalidRequest(nil, messageInvalidPath)
		}

		err := store.Init()
		if err != nil {
			return errorInternal(err, messageErrorResettingStorage)
		}

		err = apiutil.WriteJsonResponse(w, &resetResponse{Message: "Reset completed"}, http.StatusOK)
		if err != nil {
			return errorInternal(err, messageUnableToWriteResponse)
		}

	default:
		return errorInvalidRequest(nil, messageInvalidHttpMethod)
	}

	return nil
}
Beispiel #2
0
Datei: api.go Projekt: w01/sac1
// Handle requests to /item
func handleItem(w http.ResponseWriter, req *http.Request) *apiutil.Error {
	switch req.Method {

	case "GET":
		if req.URL.Path != "/item" && req.URL.Path != "/item/" {
			return errorInvalidRequest(nil, messageInvalidPath)
		}

		sl, err := store.List()
		if err != nil {
			return errorInternal(err, messageUnableToListItems)
		}

		// Storage and api schemas are not necessarily the same, translate.
		l := make([]*item, 0, len(sl))
		for _, it := range sl {
			l = append(l, &item{Id: it.Id, Value: it.Value})
		}

		err = apiutil.WriteJsonResponse(w, &listResponse{Items: l}, http.StatusOK)
		if err != nil {
			return errorInternal(err, messageUnableToWriteResponse)
		}

	case "POST":
		if req.URL.Path != "/item" && req.URL.Path != "/item/" {
			return errorInvalidRequest(nil, messageInvalidPath)
		}

		var cr createRequest
		err := json.NewDecoder(req.Body).Decode(&cr)
		if err != nil {
			return errorInvalidRequest(err, messageInvalidRequest)
		}

		if serr := validateField("value", cr.Value, limitItemValueLength); serr != nil {
			return serr
		}

		id, err := store.Create(cr.Value)
		if err != nil {
			return errorInternal(err, messageErrorCreatingItem)
		}

		err = apiutil.WriteJsonResponse(w, &createResponse{Id: id}, http.StatusOK)
		if err != nil {
			return errorInternal(err, messageUnableToWriteResponse)
		}

	case "DELETE":
		if !strings.HasPrefix(req.URL.Path, "/item/") {
			return errorInvalidRequest(nil, messageInvalidPath)
		}

		id := apiutil.LastUrlSegment(req)
		if serr := validateField("id", id, limitItemIdLength); serr != nil {
			return serr
		}

		err := store.Remove(id)
		if err != nil {
			return errorInternal(err, messageErrorRemovingItem)
		}

		err = apiutil.WriteJsonResponse(w, &deleteResponse{Id: id}, http.StatusOK)
		if err != nil {
			return errorInternal(err, messageUnableToWriteResponse)
		}

	default:
		return errorInvalidRequest(nil, messageInvalidHttpMethod)
	}

	return nil
}