code.gitea.io/gitea@v1.21.7/routers/api/packages/helper/helper.go (about) 1 // Copyright 2021 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package helper 5 6 import ( 7 "fmt" 8 "io" 9 "net/http" 10 "net/url" 11 12 packages_model "code.gitea.io/gitea/models/packages" 13 "code.gitea.io/gitea/modules/context" 14 "code.gitea.io/gitea/modules/log" 15 "code.gitea.io/gitea/modules/setting" 16 ) 17 18 // LogAndProcessError logs an error and calls a custom callback with the processed error message. 19 // If the error is an InternalServerError the message is stripped if the user is not an admin. 20 func LogAndProcessError(ctx *context.Context, status int, obj any, cb func(string)) { 21 var message string 22 if err, ok := obj.(error); ok { 23 message = err.Error() 24 } else if obj != nil { 25 message = fmt.Sprintf("%s", obj) 26 } 27 if status == http.StatusInternalServerError { 28 log.ErrorWithSkip(1, message) 29 30 if setting.IsProd && (ctx.Doer == nil || !ctx.Doer.IsAdmin) { 31 message = "" 32 } 33 } else { 34 log.Debug(message) 35 } 36 37 if cb != nil { 38 cb(message) 39 } 40 } 41 42 // Serves the content of the package file 43 // If the url is set it will redirect the request, otherwise the content is copied to the response. 44 func ServePackageFile(ctx *context.Context, s io.ReadSeekCloser, u *url.URL, pf *packages_model.PackageFile, forceOpts ...*context.ServeHeaderOptions) { 45 if u != nil { 46 ctx.Redirect(u.String()) 47 return 48 } 49 50 defer s.Close() 51 52 var opts *context.ServeHeaderOptions 53 if len(forceOpts) > 0 { 54 opts = forceOpts[0] 55 } else { 56 opts = &context.ServeHeaderOptions{ 57 Filename: pf.Name, 58 LastModified: pf.CreatedUnix.AsLocalTime(), 59 } 60 } 61 62 ctx.ServeContent(s, opts) 63 }