github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/api/server/blob.go (about)

     1  package server
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  	"os"
     8  
     9  	"github.com/gorilla/mux"
    10  )
    11  
    12  // blobGet is the handler to request a blob for a specific
    13  // repository.
    14  func (s *Server) blobGet(rw http.ResponseWriter, req *http.Request) {
    15  	vars := mux.Vars(req)
    16  	repositoryName := vars["repository"]
    17  
    18  	repository, err := s.rm.Open(repositoryName)
    19  	if err != nil {
    20  		errorText(rw, "Internal Error", http.StatusInternalServerError)
    21  		return
    22  	}
    23  
    24  	blobID := vars["blobID"]
    25  
    26  	Log.Debug(fmt.Sprintf("Repository %s: Requesting blob ID %s", repositoryName, blobID))
    27  	reader, err := repository.GetObjectData(blobID)
    28  
    29  	if err != nil {
    30  		if os.IsNotExist(err) {
    31  			Log.Debug(fmt.Sprintf("Repository %s: Could not find blob ID %s", repositoryName, blobID))
    32  			errorText(rw, "Not found", http.StatusNotFound)
    33  		} else {
    34  			Log.Warn(fmt.Sprintf("Repository %s: Could not request blob ID %s", repositoryName, blobID))
    35  			errorText(rw, "Internal Error", http.StatusInternalServerError)
    36  		}
    37  		return
    38  	}
    39  
    40  	rw.Header().Set("Content-Type", "application/octet-stream")
    41  	rw.WriteHeader(http.StatusOK)
    42  	io.Copy(rw, reader)
    43  	_ = reader.Close()
    44  }
    45  
    46  // blobPut is the handler to set the content of a blob for a specific
    47  // repository
    48  func (s *Server) blobPut(rw http.ResponseWriter, req *http.Request) {
    49  	vars := mux.Vars(req)
    50  	repositoryName := vars["repository"]
    51  
    52  	repository, err := s.rm.Open(repositoryName)
    53  	if err != nil {
    54  		errorText(rw, "Internal Error", http.StatusInternalServerError)
    55  		return
    56  	}
    57  
    58  	blobID := vars["blobID"]
    59  
    60  	Log.Debug(fmt.Sprintf("Repository: %s, Adding blob with ID %s", repositoryName, blobID))
    61  	err = repository.AddObject(blobID, req.Body)
    62  
    63  	if err != nil {
    64  		Log.Warn(
    65  			fmt.Sprintf(
    66  				"Repository: %s, Could not add blob with ID %s. Error: %s",
    67  				repositoryName, blobID, err.Error(),
    68  			),
    69  		)
    70  		errorText(rw, "Internal Error", http.StatusInternalServerError)
    71  		return
    72  	}
    73  
    74  	rw.Header().Set("Location", req.URL.String())
    75  	rw.WriteHeader(http.StatusOK)
    76  }