github.com/blend/go-sdk@v1.20220411.3/web/raw_result.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package web
     9  
    10  import (
    11  	"net"
    12  	"net/http"
    13  
    14  	"github.com/blend/go-sdk/ex"
    15  	"github.com/blend/go-sdk/webutil"
    16  )
    17  
    18  // Raw returns a new raw result.
    19  func Raw(contents []byte) *RawResult {
    20  	return &RawResult{
    21  		StatusCode:  http.StatusOK,
    22  		ContentType: http.DetectContentType(contents),
    23  		Response:    contents,
    24  	}
    25  }
    26  
    27  // RawWithContentType returns a binary response with a given content type.
    28  func RawWithContentType(contentType string, body []byte) *RawResult {
    29  	return &RawResult{
    30  		StatusCode:  http.StatusOK,
    31  		ContentType: contentType,
    32  		Response:    body,
    33  	}
    34  }
    35  
    36  // RawResult is for when you just want to dump bytes.
    37  type RawResult struct {
    38  	StatusCode  int
    39  	ContentType string
    40  	Response    []byte
    41  }
    42  
    43  // Render renders the result.
    44  func (rr *RawResult) Render(ctx *Ctx) error {
    45  	if len(rr.ContentType) != 0 {
    46  		ctx.Response.Header().Set(webutil.HeaderContentType, rr.ContentType)
    47  	}
    48  	ctx.Response.WriteHeader(rr.StatusCode)
    49  	_, err := ctx.Response.Write(rr.Response)
    50  	if err != nil {
    51  		if typed, ok := err.(*net.OpError); ok {
    52  			return ex.New(webutil.ErrNetWrite, ex.OptInner(typed))
    53  		}
    54  		return ex.New(err)
    55  	}
    56  	return nil
    57  }