go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/raw_result.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package web
     9  
    10  import (
    11  	"net/http"
    12  
    13  	"go.charczuk.com/sdk/errutil"
    14  )
    15  
    16  // Raw returns a new raw result.
    17  func Raw(contents []byte) *RawResult {
    18  	return &RawResult{
    19  		StatusCode:  http.StatusOK,
    20  		ContentType: http.DetectContentType(contents),
    21  		Response:    contents,
    22  	}
    23  }
    24  
    25  // RawString returns a new text result.
    26  func RawString(contents string) *RawResult {
    27  	return &RawResult{
    28  		StatusCode:  http.StatusOK,
    29  		ContentType: ContentTypeText,
    30  		Response:    []byte(contents),
    31  	}
    32  }
    33  
    34  // RawWithContentType returns a binary response with a given content type.
    35  func RawWithContentType(contentType string, body []byte) *RawResult {
    36  	return &RawResult{
    37  		StatusCode:  http.StatusOK,
    38  		ContentType: contentType,
    39  		Response:    body,
    40  	}
    41  }
    42  
    43  // RawWithErr returns a binary response with a given application error.
    44  func RawWithErr(contentType string, body []byte, err error) *RawResult {
    45  	return &RawResult{
    46  		StatusCode:  http.StatusOK,
    47  		ContentType: contentType,
    48  		Response:    body,
    49  		Err:         err,
    50  	}
    51  }
    52  
    53  // RawResult is for when you just want to dump bytes.
    54  type RawResult struct {
    55  	StatusCode  int
    56  	ContentType string
    57  	Response    []byte
    58  	Err         error
    59  }
    60  
    61  // Render renders the result.
    62  func (rr *RawResult) Render(ctx Context) error {
    63  	if rr.ContentType != "" {
    64  		ctx.Response().Header().Set(HeaderContentType, rr.ContentType)
    65  	}
    66  	ctx.Response().WriteHeader(rr.StatusCode)
    67  	_, err := ctx.Response().Write(rr.Response)
    68  	return errutil.Append(err, rr.Err)
    69  }