コード例 #1
0
// Post ...
func (r *RequestResource) Post() http.HandlerFunc {
	return func(rw http.ResponseWriter, req *http.Request) {
		apiIncomingRequest, err := r.DecodeInputRequest(req.Body)
		if err != nil {
			log.Printf("incoming-request-decode-error: %v", err)
			http.Error(rw, err.Error(), http.StatusBadRequest)
			return
		}

		err = r.ValidateIncomingRequest(apiIncomingRequest)
		if err != nil {
			log.Printf("incoming-request-validation-error: %v", err)
			http.Error(rw, err.Error(), http.StatusBadRequest)
			return
		}

		inReq := download.FromAPIIncomingRequest(apiIncomingRequest)
		downloadRequest, err := r.RequestService.ProcessNewRequest(inReq)

		if err != nil {
			log.Printf("request-processing-error: %v", err)
			rw.Header().Set("Content-Type", "application/json")
			rw.WriteHeader(http.StatusInternalServerError)
			encoder := json.NewEncoder(rw)
			encErr := encoder.Encode(r.WrapError(err))
			if encErr != nil {
				log.Printf("encode-error: %v", encErr)
			}
		} else {
			newURL, _ := r.GetRequestURL(downloadRequest.ID)
			rw.Header().Set("Content-Type", "application/json")
			rw.Header().Set("Location", newURL.String())
			rw.WriteHeader(http.StatusAccepted)
			encoder := json.NewEncoder(rw)
			dr := download.ToAPIRequest(downloadRequest)
			r.populateLinks(req, dr)
			encErr := encoder.Encode(dr)
			if encErr != nil {
				log.Printf("encode-error: %v", encErr)
			}

		}
	}
}
コード例 #2
0
// Get ...
func (r *RequestResource) Get() http.HandlerFunc {
	return func(rw http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		requestID := vars["id"]

		downloadRequest, err := r.RequestService.FindByID(requestID)

		encoder := json.NewEncoder(rw)
		rw.Header().Set("Content-Type", "application/json")

		if err != nil {
			log.Printf("server-error: %v", err)
			rw.WriteHeader(http.StatusInternalServerError)
			encErr := encoder.Encode(r.WrapError(err))
			if encErr != nil {
				log.Printf("encode-error: %v", encErr)
			}
		} else if downloadRequest != nil {
			rw.WriteHeader(http.StatusOK)
			dr := download.ToAPIRequest(downloadRequest)
			r.populateLinks(req, dr)
			encErr := encoder.Encode(dr)
			if encErr != nil {
				log.Printf("encode-error: %v", encErr)
			}
		} else {
			errMessage := fmt.Sprintf("Unable to find request with id:%s", requestID)
			log.Printf("server-error: %v", errMessage)

			rw.WriteHeader(http.StatusNotFound)
			encErr := encoder.Encode(errors.New(errMessage))
			if encErr != nil {
				log.Printf("encode-error: %v", encErr)
			}
		}
	}
}