go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/json_result_provider.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 14 var ( 15 // assert it implements result provider. 16 _ ResultProvider = (*JSONResultProvider)(nil) 17 ) 18 19 // JSON returns a json result provider. 20 func JSON() JSONResultProvider { 21 return JSONResultProvider{} 22 } 23 24 // JSONResultProvider are context results for api methods. 25 type JSONResultProvider struct{} 26 27 // NotFound returns a service response. 28 func (jrp JSONResultProvider) NotFound() Result { 29 return &JSONResult{ 30 StatusCode: http.StatusNotFound, 31 Response: http.StatusText(http.StatusNotFound), 32 } 33 } 34 35 // NotAuthorized returns a service response. 36 func (jrp JSONResultProvider) NotAuthorized() Result { 37 return &JSONResult{ 38 StatusCode: http.StatusUnauthorized, 39 Response: http.StatusText(http.StatusUnauthorized), 40 } 41 } 42 43 // Forbidden returns a service response. 44 func (jrp JSONResultProvider) Forbidden() Result { 45 return &JSONResult{ 46 StatusCode: http.StatusForbidden, 47 Response: http.StatusText(http.StatusForbidden), 48 } 49 } 50 51 // InternalError returns a json response. 52 func (jrp JSONResultProvider) InternalError(err error) Result { 53 return &JSONResult{ 54 StatusCode: http.StatusInternalServerError, 55 Response: err.Error(), 56 Err: err, 57 } 58 } 59 60 // BadRequest returns a json response. 61 func (jrp JSONResultProvider) BadRequest(err error) Result { 62 return &JSONResult{ 63 StatusCode: http.StatusBadRequest, 64 Response: err.Error(), 65 } 66 } 67 68 // OK returns a json response. 69 func (jrp JSONResultProvider) OK() Result { 70 return &JSONResult{ 71 StatusCode: http.StatusOK, 72 Response: "OK!", 73 } 74 } 75 76 // Result returns a json response. 77 func (jrp JSONResultProvider) Result(statusCode int, result any) Result { 78 return &JSONResult{ 79 StatusCode: statusCode, 80 Response: result, 81 } 82 }