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

     1  package server
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io/ioutil"
     7  
     8  	"net/http"
     9  
    10  	"github.com/gorilla/mux"
    11  
    12  	"github.com/hoffie/larasync/api"
    13  )
    14  
    15  // repositoryList returns a list of all configured repositories.
    16  func (s *Server) repositoryList(rw http.ResponseWriter, req *http.Request) {
    17  	jsonHeader(rw)
    18  	names, err := s.rm.ListNames()
    19  	if err != nil {
    20  		errorJSONMessage(rw, "Internal Server Error", http.StatusInternalServerError)
    21  		return
    22  	}
    23  	out, err := json.Marshal(names)
    24  	if err != nil {
    25  		errorJSONMessage(rw, "Internal Server Error", http.StatusInternalServerError)
    26  		return
    27  	}
    28  	rw.Write(out)
    29  }
    30  
    31  func (s *Server) repositoryCreate(rw http.ResponseWriter, req *http.Request) {
    32  	jsonHeader(rw)
    33  	vars := mux.Vars(req)
    34  	repositoryName := vars["repository"]
    35  	if s.rm.Exists(repositoryName) {
    36  		errorJSONMessage(rw, "Repository exists", http.StatusConflict)
    37  		return
    38  	}
    39  	var repository api.JSONRepository
    40  	body, err := ioutil.ReadAll(req.Body)
    41  	if err != nil {
    42  		errorJSONMessage(rw, "Internal Server Error", http.StatusInternalServerError)
    43  		return
    44  	}
    45  
    46  	err = json.Unmarshal(body, &repository)
    47  	if err != nil {
    48  		errorJSONMessage(rw, "Bad Request", http.StatusBadRequest)
    49  		return
    50  	}
    51  
    52  	if len(repository.PubKey) != PublicKeySize {
    53  		errorMessage := fmt.Sprintf(
    54  			"Public key has to be of length %d got %d",
    55  			PublicKeySize,
    56  			len(repository.PubKey))
    57  		errorJSONMessage(
    58  			rw,
    59  			errorMessage,
    60  			http.StatusBadRequest)
    61  	}
    62  
    63  	err = s.rm.Create(repositoryName, repository.PubKey)
    64  	if err != nil {
    65  		errorJSONMessage(rw, "Internal Server Error", http.StatusInternalServerError)
    66  		return
    67  	}
    68  
    69  	rw.WriteHeader(http.StatusCreated)
    70  
    71  }