github.com/maeglindeveloper/gqlgen@v0.13.1-0.20210413081235-57808b12a0a0/graphql/handler/transport/http_post.go (about)

     1  package transport
     2  
     3  import (
     4  	"mime"
     5  	"net/http"
     6  
     7  	"github.com/99designs/gqlgen/graphql"
     8  )
     9  
    10  // POST implements the POST side of the default HTTP transport
    11  // defined in https://github.com/APIs-guru/graphql-over-http#post
    12  type POST struct{}
    13  
    14  var _ graphql.Transport = POST{}
    15  
    16  func (h POST) Supports(r *http.Request) bool {
    17  	if r.Header.Get("Upgrade") != "" {
    18  		return false
    19  	}
    20  
    21  	mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
    22  	if err != nil {
    23  		return false
    24  	}
    25  
    26  	return r.Method == "POST" && mediaType == "application/json"
    27  }
    28  
    29  func (h POST) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor) {
    30  	w.Header().Set("Content-Type", "application/json")
    31  
    32  	var params *graphql.RawParams
    33  	start := graphql.Now()
    34  	if err := jsonDecode(r.Body, &params); err != nil {
    35  		w.WriteHeader(http.StatusBadRequest)
    36  		writeJsonErrorf(w, "json body could not be decoded: "+err.Error())
    37  		return
    38  	}
    39  	params.ReadTime = graphql.TraceTiming{
    40  		Start: start,
    41  		End:   graphql.Now(),
    42  	}
    43  
    44  	rc, err := exec.CreateOperationContext(r.Context(), params)
    45  	if err != nil {
    46  		w.WriteHeader(statusFor(err))
    47  		resp := exec.DispatchError(graphql.WithOperationContext(r.Context(), rc), err)
    48  		writeJson(w, resp)
    49  		return
    50  	}
    51  	ctx := graphql.WithOperationContext(r.Context(), rc)
    52  	responses, ctx := exec.DispatchOperation(ctx, rc)
    53  	writeJson(w, responses(ctx))
    54  }