You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.8 KiB

  1. package s3api
  2. import (
  3. "net/http"
  4. "net/url"
  5. "fmt"
  6. "time"
  7. "github.com/gorilla/mux"
  8. "context"
  9. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  10. "github.com/chrislusf/seaweedfs/weed/util"
  11. )
  12. func newContext(r *http.Request, api string) context.Context {
  13. vars := mux.Vars(r)
  14. return context.WithValue(context.Background(), "bucket", vars["bucket"])
  15. }
  16. func (s3a *S3ApiServer) withFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  17. grpcConnection, err := util.GrpcDial(s3a.option.FilerGrpcAddress)
  18. if err != nil {
  19. return fmt.Errorf("fail to dial %s: %v", s3a.option.FilerGrpcAddress, err)
  20. }
  21. defer grpcConnection.Close()
  22. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  23. return fn(client)
  24. }
  25. // If none of the http routes match respond with MethodNotAllowed
  26. func notFoundHandler(w http.ResponseWriter, r *http.Request) {
  27. writeErrorResponse(w, ErrMethodNotAllowed, r.URL)
  28. }
  29. func writeErrorResponse(w http.ResponseWriter, errorCode ErrorCode, reqURL *url.URL) {
  30. apiError := getAPIError(errorCode)
  31. errorResponse := getRESTErrorResponse(apiError, reqURL.Path)
  32. encodedErrorResponse := encodeResponse(errorResponse)
  33. writeResponse(w, apiError.HTTPStatusCode, encodedErrorResponse, mimeXML)
  34. }
  35. func getRESTErrorResponse(err APIError, resource string) RESTErrorResponse {
  36. return RESTErrorResponse{
  37. Code: err.Code,
  38. Message: err.Description,
  39. Resource: resource,
  40. RequestID: fmt.Sprintf("%d", time.Now().UnixNano()),
  41. }
  42. }
  43. func writeResponse(w http.ResponseWriter, statusCode int, response []byte, mType mimeType) {
  44. setCommonHeaders(w)
  45. if mType != mimeNone {
  46. w.Header().Set("Content-Type", string(mType))
  47. }
  48. w.WriteHeader(statusCode)
  49. if response != nil {
  50. w.Write(response)
  51. w.(http.Flusher).Flush()
  52. }
  53. }
  54. func writeSuccessResponseXML(w http.ResponseWriter, response []byte) {
  55. writeResponse(w, http.StatusOK, response, mimeXML)
  56. }