Best Syzkaller code snippet using asset.upload
store.go
Source:store.go
...83 // testing hooks84 testing bool // true if we're in a test85 keyTester func(encKey, sigKey []byte) // used for testing only to check key changes86 aborts int // number of aborts87 blockLimit int // max number of blocks to upload88}89// NewS3Store creates a standard Store that uses a real90// S3 connection.91func NewS3Store(logger logger.Logger, env *libkb.Env, runtimeDir string) *S3Store {92 return &S3Store{93 DebugLabeler: utils.NewDebugLabeler(logger, "Attachments.Store", false),94 s3c: &s3.AWS{},95 stash: NewFileStash(runtimeDir),96 env: env,97 }98}99// NewStoreTesting creates an Store suitable for testing100// purposes. It is not exposed outside this package.101// It uses an in-memory s3 interface, reports enc/sig keys, and allows limiting102// the number of blocks uploaded.103func NewStoreTesting(log logger.Logger, kt func(enc, sig []byte)) *S3Store {104 return &S3Store{105 DebugLabeler: utils.NewDebugLabeler(log, "Attachments.Store", false),106 s3c: &s3.Mem{},107 stash: NewFileStash(os.TempDir()),108 keyTester: kt,109 testing: true,110 env: libkb.NewEnv(nil, nil, func() logger.Logger { return log }),111 }112}113func (a *S3Store) UploadAsset(ctx context.Context, task *UploadTask, encryptedOut io.Writer) (res chat1.Asset, err error) {114 defer a.Trace(ctx, func() error { return err }, "UploadAsset")()115 // compute plaintext hash116 if task.hash() == nil {117 task.computeHash()118 } else {119 if !a.testing {120 return res, errors.New("task.plaintextHash not nil")121 }122 a.Debug(ctx, "UploadAsset: skipping plaintextHash calculation due to existing plaintextHash (testing only feature)")123 }124 // encrypt the stream125 enc := NewSignEncrypter()126 len := enc.EncryptedLen(task.FileSize)127 // check for previous interrupted upload attempt128 var previous *AttachmentInfo129 resumable := len > minMultiSize // can only resume multi uploads130 if resumable {131 previous = a.previousUpload(ctx, task)132 }133 res, err = a.uploadAsset(ctx, task, enc, previous, resumable, encryptedOut)134 // if the upload is aborted, reset the stream and start over to get new keys135 if err == ErrAbortOnPartMismatch && previous != nil {136 a.Debug(ctx, "UploadAsset: resume call aborted, resetting stream and starting from scratch")137 a.aborts++138 previous = nil139 task.Plaintext.Reset()140 task.computeHash()141 return a.uploadAsset(ctx, task, enc, nil, resumable, encryptedOut)142 }143 return res, err144}145func (a *S3Store) uploadAsset(ctx context.Context, task *UploadTask, enc *SignEncrypter,146 previous *AttachmentInfo, resumable bool, encryptedOut io.Writer) (asset chat1.Asset, err error) {147 defer a.Trace(ctx, func() error { return err }, "uploadAsset")()148 var encReader io.Reader149 if previous != nil {150 a.Debug(ctx, "uploadAsset: found previous upload for %s in conv %s", task.Filename,151 task.ConversationID)152 encReader, err = enc.EncryptResume(task.Plaintext, task.Nonce(), previous.EncKey, previous.SignKey, previous.VerifyKey)153 if err != nil {154 return chat1.Asset{}, err155 }156 } else {157 encReader, err = enc.EncryptWithNonce(task.Plaintext, task.Nonce())158 if err != nil {159 return chat1.Asset{}, err160 }161 if resumable {162 a.startUpload(ctx, task, enc)163 }164 }165 if a.testing && a.keyTester != nil {166 a.Debug(ctx, "uploadAsset: Store.keyTester exists, reporting keys")167 a.keyTester(enc.EncryptKey(), enc.VerifyKey())168 }169 // compute ciphertext hash170 hash := sha256.New()171 tee := io.TeeReader(io.TeeReader(encReader, hash), encryptedOut)172 // post to s3173 length := int64(enc.EncryptedLen(task.FileSize))174 upRes, err := a.PutS3(ctx, tee, length, task, previous)175 if err != nil {176 if err == ErrAbortOnPartMismatch && previous != nil {177 // erase information about previous upload attempt178 a.finishUpload(ctx, task)179 }180 ew, ok := err.(*ErrorWrapper)181 if ok {182 a.Debug(ctx, "uploadAsset: PutS3 error details: %s", ew.Details())183 }184 return chat1.Asset{}, err185 }186 a.Debug(ctx, "uploadAsset: chat attachment upload: %+v", upRes)187 asset = chat1.Asset{188 Filename: filepath.Base(task.Filename),189 Region: upRes.Region,190 Endpoint: upRes.Endpoint,191 Bucket: upRes.Bucket,192 Path: upRes.Path,193 Size: upRes.Size,194 Key: enc.EncryptKey(),195 VerifyKey: enc.VerifyKey(),196 EncHash: hash.Sum(nil),197 Nonce: task.Nonce()[:],198 }199 if resumable {200 a.finishUpload(ctx, task)...
http.go
Source:http.go
1// Package http implements functionality common to HTTP uploading pipelines.2package http3import (4 "crypto/tls"5 "crypto/x509"6 "fmt"7 "io"8 h "net/http"9 "os"10 "runtime"11 "strings"12 "github.com/caarlos0/log"13 "github.com/goreleaser/goreleaser/internal/artifact"14 "github.com/goreleaser/goreleaser/internal/pipe"15 "github.com/goreleaser/goreleaser/internal/semerrgroup"16 "github.com/goreleaser/goreleaser/internal/tmpl"17 "github.com/goreleaser/goreleaser/pkg/config"18 "github.com/goreleaser/goreleaser/pkg/context"19)20const (21 // ModeBinary uploads only compiled binaries.22 ModeBinary = "binary"23 // ModeArchive uploads release archives.24 ModeArchive = "archive"25)26type asset struct {27 ReadCloser io.ReadCloser28 Size int6429}30type assetOpenFunc func(string, *artifact.Artifact) (*asset, error)31// nolint: gochecknoglobals32var assetOpen assetOpenFunc33// TODO: fix this.34// nolint: gochecknoinits35func init() {36 assetOpenReset()37}38func assetOpenReset() {39 assetOpen = assetOpenDefault40}41func assetOpenDefault(kind string, a *artifact.Artifact) (*asset, error) {42 f, err := os.Open(a.Path)43 if err != nil {44 return nil, err45 }46 s, err := f.Stat()47 if err != nil {48 return nil, err49 }50 if s.IsDir() {51 return nil, fmt.Errorf("%s: upload failed: the asset to upload can't be a directory", kind)52 }53 return &asset{54 ReadCloser: f,55 Size: s.Size(),56 }, nil57}58// Defaults sets default configuration options on upload structs.59func Defaults(uploads []config.Upload) error {60 for i := range uploads {61 defaults(&uploads[i])62 }63 return nil64}65func defaults(upload *config.Upload) {66 if upload.Mode == "" {67 upload.Mode = ModeArchive68 }69 if upload.Method == "" {70 upload.Method = h.MethodPut71 }72}73// CheckConfig validates an upload configuration returning a descriptive error when appropriate.74func CheckConfig(ctx *context.Context, upload *config.Upload, kind string) error {75 if upload.Target == "" {76 return misconfigured(kind, upload, "missing target")77 }78 if upload.Name == "" {79 return misconfigured(kind, upload, "missing name")80 }81 if upload.Mode != ModeArchive && upload.Mode != ModeBinary {82 return misconfigured(kind, upload, "mode must be 'binary' or 'archive'")83 }84 username := getUsername(ctx, upload, kind)85 password := getPassword(ctx, upload, kind)86 passwordEnv := fmt.Sprintf("%s_%s_SECRET", strings.ToUpper(kind), strings.ToUpper(upload.Name))87 if password != "" && username == "" {88 return misconfigured(kind, upload, fmt.Sprintf("'username' is required when '%s' environment variable is set", passwordEnv))89 }90 if username != "" && password == "" {91 return misconfigured(kind, upload, fmt.Sprintf("environment variable '%s' is required when 'username' is set", passwordEnv))92 }93 if upload.TrustedCerts != "" && !x509.NewCertPool().AppendCertsFromPEM([]byte(upload.TrustedCerts)) {94 return misconfigured(kind, upload, "no certificate could be added from the specified trusted_certificates configuration")95 }96 if upload.ClientX509Cert != "" && upload.ClientX509Key == "" {97 return misconfigured(kind, upload, "'client_x509_key' must be set when 'client_x509_cert' is set")98 }99 if upload.ClientX509Key != "" && upload.ClientX509Cert == "" {100 return misconfigured(kind, upload, "'client_x509_cert' must be set when 'client_x509_key' is set")101 }102 if upload.ClientX509Cert != "" && upload.ClientX509Key != "" {103 if _, err := tls.LoadX509KeyPair(upload.ClientX509Cert, upload.ClientX509Key); err != nil {104 return misconfigured(kind, upload,105 "client x509 certificate could not be loaded from the specified 'client_x509_cert' and 'client_x509_key'")106 }107 }108 return nil109}110// username is optional111func getUsername(ctx *context.Context, upload *config.Upload, kind string) string {112 if upload.Username != "" {113 return upload.Username114 }115 key := fmt.Sprintf("%s_%s_USERNAME", strings.ToUpper(kind), strings.ToUpper(upload.Name))116 return ctx.Env[key]117}118// password is optional119func getPassword(ctx *context.Context, upload *config.Upload, kind string) string {120 key := fmt.Sprintf("%s_%s_SECRET", strings.ToUpper(kind), strings.ToUpper(upload.Name))121 return ctx.Env[key]122}123func misconfigured(kind string, upload *config.Upload, reason string) error {124 return pipe.Skip(fmt.Sprintf("%s section '%s' is not configured properly (%s)", kind, upload.Name, reason))125}126// ResponseChecker is a function capable of validating an http server response.127// It must return and error when the response must be considered a failure.128type ResponseChecker func(*h.Response) error129// Upload does the actual uploading work.130func Upload(ctx *context.Context, uploads []config.Upload, kind string, check ResponseChecker) error {131 // Handle every configured upload132 for _, upload := range uploads {133 upload := upload134 filters := []artifact.Filter{}135 if upload.Checksum {136 filters = append(filters, artifact.ByType(artifact.Checksum))137 }138 if upload.Signature {139 filters = append(filters, artifact.ByType(artifact.Signature), artifact.ByType(artifact.Certificate))140 }141 // We support two different modes142 // - "archive": Upload all artifacts143 // - "binary": Upload only the raw binaries144 switch v := strings.ToLower(upload.Mode); v {145 case ModeArchive:146 // TODO: should we add source archives here too?147 filters = append(filters,148 artifact.ByType(artifact.UploadableArchive),149 artifact.ByType(artifact.LinuxPackage),150 )151 case ModeBinary:152 filters = append(filters, artifact.ByType(artifact.UploadableBinary))153 default:154 err := fmt.Errorf("%s: mode \"%s\" not supported", kind, v)155 log.WithFields(log.Fields{156 kind: upload.Name,157 "mode": v,158 }).Error(err.Error())159 return err160 }161 filter := artifact.Or(filters...)162 if len(upload.IDs) > 0 {163 filter = artifact.And(filter, artifact.ByIDs(upload.IDs...))164 }165 if len(upload.Exts) > 0 {166 filter = artifact.And(filter, artifact.ByExt(upload.Exts...))167 }168 if err := uploadWithFilter(ctx, &upload, filter, kind, check); err != nil {169 return err170 }171 }172 return nil173}174func uploadWithFilter(ctx *context.Context, upload *config.Upload, filter artifact.Filter, kind string, check ResponseChecker) error {175 artifacts := ctx.Artifacts.Filter(filter).List()176 log.Debugf("will upload %d artifacts", len(artifacts))177 g := semerrgroup.New(ctx.Parallelism)178 for _, artifact := range artifacts {179 artifact := artifact180 g.Go(func() error {181 return uploadAsset(ctx, upload, artifact, kind, check)182 })183 }184 return g.Wait()185}186// uploadAsset uploads file to target and logs all actions.187func uploadAsset(ctx *context.Context, upload *config.Upload, artifact *artifact.Artifact, kind string, check ResponseChecker) error {188 // username and secret are optional since the server may not support/need189 // basic authentication always190 username := getUsername(ctx, upload, kind)191 secret := getPassword(ctx, upload, kind)192 // Generate the target url193 targetURL, err := resolveTargetTemplate(ctx, upload, artifact)194 if err != nil {195 msg := fmt.Sprintf("%s: error while building the target url", kind)196 log.WithField("instance", upload.Name).WithError(err).Error(msg)197 return fmt.Errorf("%s: %w", msg, err)198 }199 // Handle the artifact200 asset, err := assetOpen(kind, artifact)201 if err != nil {202 return err203 }204 defer asset.ReadCloser.Close()205 // target url need to contain the artifact name unless the custom206 // artifact name is used207 if !upload.CustomArtifactName {208 if !strings.HasSuffix(targetURL, "/") {209 targetURL += "/"210 }211 targetURL += artifact.Name212 }213 log.Debugf("generated target url: %s", targetURL)214 headers := map[string]string{}215 if upload.CustomHeaders != nil {216 for name, value := range upload.CustomHeaders {217 resolvedValue, err := resolveHeaderTemplate(ctx, upload, artifact, value)218 if err != nil {219 msg := fmt.Sprintf("%s: failed to resolve custom_headers template", kind)220 log.WithError(err).WithFields(log.Fields{221 "instance": upload.Name,222 "header_name": name,223 "header_value": value,224 }).Error(msg)225 return fmt.Errorf("%s: %w", msg, err)226 }227 headers[name] = resolvedValue228 }229 }230 if upload.ChecksumHeader != "" {231 sum, err := artifact.Checksum("sha256")232 if err != nil {233 return err234 }235 headers[upload.ChecksumHeader] = sum236 }237 res, err := uploadAssetToServer(ctx, upload, targetURL, username, secret, headers, asset, check)238 if err != nil {239 msg := fmt.Sprintf("%s: upload failed", kind)240 log.WithError(err).WithFields(log.Fields{241 "instance": upload.Name,242 }).Error(msg)243 return fmt.Errorf("%s: %w", msg, err)244 }245 if err := res.Body.Close(); err != nil {246 log.WithError(err).Warn("failed to close response body")247 }248 log.WithFields(log.Fields{249 "instance": upload.Name,250 "mode": upload.Mode,251 }).Info("uploaded successful")252 return nil253}254// uploadAssetToServer uploads the asset file to target.255func uploadAssetToServer(ctx *context.Context, upload *config.Upload, target, username, secret string, headers map[string]string, a *asset, check ResponseChecker) (*h.Response, error) {256 req, err := newUploadRequest(ctx, upload.Method, target, username, secret, headers, a)257 if err != nil {258 return nil, err259 }260 return executeHTTPRequest(ctx, upload, req, check)261}262// newUploadRequest creates a new h.Request for uploading.263func newUploadRequest(ctx *context.Context, method, target, username, secret string, headers map[string]string, a *asset) (*h.Request, error) {264 req, err := h.NewRequestWithContext(ctx, method, target, a.ReadCloser)265 if err != nil {266 return nil, err267 }268 req.ContentLength = a.Size269 if username != "" && secret != "" {270 req.SetBasicAuth(username, secret)271 }272 for k, v := range headers {273 req.Header.Add(k, v)274 }275 return req, err276}277func getHTTPClient(upload *config.Upload) (*h.Client, error) {278 if upload.TrustedCerts == "" && upload.ClientX509Cert == "" && upload.ClientX509Key == "" {279 return h.DefaultClient, nil280 }281 transport := &h.Transport{282 Proxy: h.ProxyFromEnvironment,283 TLSClientConfig: &tls.Config{},284 }285 if upload.TrustedCerts != "" {286 pool, err := x509.SystemCertPool()287 if err != nil {288 if runtime.GOOS == "windows" {289 // on windows ignore errors until golang issues #16736 & #18609 get fixed290 pool = x509.NewCertPool()291 } else {292 return nil, err293 }294 }295 pool.AppendCertsFromPEM([]byte(upload.TrustedCerts)) // already validated certs checked by CheckConfig296 transport.TLSClientConfig.RootCAs = pool297 }298 if upload.ClientX509Cert != "" && upload.ClientX509Key != "" {299 cert, err := tls.LoadX509KeyPair(upload.ClientX509Cert, upload.ClientX509Key)300 if err != nil {301 return nil, err302 }303 transport.TLSClientConfig.Certificates = []tls.Certificate{cert}304 }305 return &h.Client{Transport: transport}, nil306}307// executeHTTPRequest processes the http call with respect of context ctx.308func executeHTTPRequest(ctx *context.Context, upload *config.Upload, req *h.Request, check ResponseChecker) (*h.Response, error) {309 client, err := getHTTPClient(upload)310 if err != nil {311 return nil, err312 }313 log.Debugf("executing request: %s %s (headers: %v)", req.Method, req.URL, req.Header)314 resp, err := client.Do(req)315 if err != nil {316 // If we got an error, and the context has been canceled,317 // the context's error is probably more useful.318 select {319 case <-ctx.Done():320 return nil, ctx.Err()321 default:322 }323 return nil, err324 }325 defer resp.Body.Close()326 err = check(resp)327 if err != nil {328 // even though there was an error, we still return the response329 // in case the caller wants to inspect it further330 return resp, err331 }332 return resp, err333}334// resolveTargetTemplate returns the resolved target template with replaced variables335// Those variables can be replaced by the given context, goos, goarch, goarm and more.336func resolveTargetTemplate(ctx *context.Context, upload *config.Upload, artifact *artifact.Artifact) (string, error) {337 replacements := map[string]string{}338 if upload.Mode == ModeBinary {339 // TODO: multiple archives here340 replacements = ctx.Config.Archives[0].Replacements341 }342 return tmpl.New(ctx).343 WithArtifact(artifact, replacements).344 Apply(upload.Target)345}346// resolveHeaderTemplate returns the resolved custom header template with replaced variables347// Those variables can be replaced by the given context, goos, goarch, goarm and more.348func resolveHeaderTemplate(ctx *context.Context, upload *config.Upload, artifact *artifact.Artifact, headerValue string) (string, error) {349 replacements := map[string]string{}350 if upload.Mode == ModeBinary {351 // TODO: multiple archives here352 replacements = ctx.Config.Archives[0].Replacements353 }354 return tmpl.New(ctx).355 WithArtifact(artifact, replacements).356 Apply(headerValue)357}...
asset.go
Source:asset.go
...46 Storage storage.Storage47 UploadHandler UploadHandler48 DeleteHandler DeleteHandler49}50// Serve the upload handler51func (m Manager) ServeHTTP(w http.ResponseWriter, r *http.Request) {52 switch r.Method {53 default:54 w.WriteHeader(http.StatusMethodNotAllowed)55 return56 case http.MethodDelete:57 m.Delete(w, r)58 case http.MethodPost:59 m.Create(w, r)60 }61}62func (m Manager) Create(w http.ResponseWriter, r *http.Request) {63 var (64 kind = strings.TrimPrefix(r.URL.Path, m.Prefix)65 ctx = r.Context()66 validator, ok = m.validators[kind]67 storageError *StorageError68 err error69 asset Asset70 response []byte71 resCode int72 )73 if !ok {74 w.WriteHeader(http.StatusNotFound)75 return76 }77 defer func() {78 if storageError == nil {79 response = []byte(`{"uri": "` + asset.URI + `"}`)80 resCode = http.StatusOK81 } else {82 var msg = strings.Replace(storageError.Message, `"`, "", -1)83 response = []byte(`{"error": "` + msg + `"}`)84 resCode = storageError.Code85 fmt.Println(">>> ", resCode)86 }87 w.Header().Set("Content-Type", "application/json")88 w.Write(response)89 w.WriteHeader(resCode)90 }()91 var body = util.ReadAll(r.Body)92 if body == nil {93 storageError = &StorageError{94 Code: http.StatusRequestEntityTooLarge,95 }96 return97 }98 var query = r.URL.Query()99 asset.Name = query.Get("name")100 asset.Resource = query.Get("resource")101 asset.ResourceID = query.Get("resource_id")102 if asset.Name == "" {103 storageError = &StorageError{104 Code: http.StatusBadRequest,105 Message: "missing query parameter: name",106 }107 } else if asset.Resource == "" {108 storageError = &StorageError{109 Code: http.StatusBadRequest,110 Message: "missing query parameter: resource",111 }112 } else if asset.ResourceID == "" {113 storageError = &StorageError{114 Code: http.StatusBadRequest,115 Message: "missing query parameter: resource_id",116 }117 }118 if storageError != nil {119 return120 }121 asset.ID = uuid.NewString()122 asset.Size = len(body)123 asset.Mime = http.DetectContentType(body)124 if i := strings.IndexRune(asset.Mime, ';'); i != -1 {125 asset.Mime = asset.Mime[:i]126 }127 if e := validator.Validate(128 ctx,129 &ValidateArgs{130 Request: r,131 Kind: kind,132 Asset: asset,133 Data: body,134 }); e != nil {135 storageError = &StorageError{136 Code: http.StatusBadRequest,137 Message: e.Error(),138 }139 return140 }141 if asset, err = m.store(ctx, asset, body); err != nil {142 storageError = &StorageError{143 Code: http.StatusInternalServerError,144 Message: "failed to store file: " + err.Error(),145 }146 return147 }148 if m.UploadHandler != nil {149 asset, storageError = m.UploadHandler.OnUpload(150 ctx,151 &UploadHandlerArgs{152 Request: r,153 Storage: m.Storage,154 Kind: kind,155 Asset: asset,156 },157 )158 return159 }160}161func (m Manager) store(ctx context.Context, asset Asset, d []byte) (Asset, error) {162 var (163 filename = filepath.Join(asset.ID, asset.Name)164 ten = tenant.Get(ctx)165 )166 var err = m.Storage.Store(ctx, filename, d)167 if err != nil {168 return asset, err169 }170 asset.URI = path.Join(m.BaseURL, ten, asset.ID, asset.Name)171 return asset, err172}173func (m Manager) Delete(w http.ResponseWriter, r *http.Request) {174 var (175 path = strings.TrimPrefix(r.URL.Path, m.Prefix)176 asset Asset177 kind string178 err *StorageError179 ctx = r.Context()180 )181 if i := strings.IndexRune(path, '/'); i != -1 {182 kind, asset.ID = path[:i], path[i+1:]183 }184 if _, ok := m.validators[kind]; !ok {185 w.WriteHeader(http.StatusNotFound)186 return187 }188 if e := m.Storage.Delete(ctx, asset.ID); e != nil {189 err = &StorageError{190 Code: http.StatusInternalServerError,191 Message: "failed to delete file: " + e.Error(),192 }193 }194 if err != nil {195 var msg = strings.Replace(err.Message, `"`, "", -1)196 w.Write([]byte(`{"error": "` + msg + `"}`))197 w.WriteHeader(err.Code)198 return199 }200 if r.Method == http.MethodDelete && m.DeleteHandler != nil {201 err = m.DeleteHandler.OnDelete(202 ctx,203 &DeleteHandlerArgs{204 Request: r,205 Storage: m.Storage,206 Kind: kind,207 ID: asset.ID,208 },209 )210 }211 w.WriteHeader(http.StatusOK)212}213// Register a validator214func (m *Manager) Register(kind string, validator Validator) *Manager {215 if m.validators == nil {216 m.validators = make(map[string]Validator)217 }218 m.validators[kind] = validator219 return m220}221func (m *Manager) Uploads() []Upload {222 var (223 uploads []Upload224 prefix = strings.TrimSuffix(m.Prefix, "/")225 )226 if i := strings.LastIndexByte(prefix, '/'); i == -1 {227 prefix = "/"228 } else {229 prefix = prefix[i:]230 }231 for kind := range m.validators {232 if t, ok := m.validators[kind].(Types); ok {233 var u = upload{234 types: t.Types(),235 path: prefix + "/" + kind,236 }237 uploads = append(uploads, u)238 }239 }240 return uploads241}242type ValidateArgs struct {243 Request *http.Request244 Kind string245 Asset Asset246 Data []byte247}248// Validator for upload249type Validator interface {250 Validate(ctx context.Context, args *ValidateArgs) error251}252// Types reports which media types are supported by a validator if the validator is validates media types253type Types interface {254 Types() []string255}256// Upload defines media uploading paths compatible with openapi interface257type Upload interface {258 Path() string259 Types() []string260}261type upload struct {262 types []string263 path string264}265func (u upload) Types() []string {266 return u.types267}268func (u upload) Path() string {269 return u.path270}271// UploadHandlerArgs represents arguments to the upload handler272type UploadHandlerArgs struct {273 Request *http.Request274 Storage storage.Storage275 Kind string276 Asset Asset277}278// UploadHandler allows a callback to a new upload279type UploadHandler interface {280 OnUpload(ctx context.Context, args *UploadHandlerArgs) (Asset, *StorageError)281}282type compositeUploadHandler struct {283 Handlers []UploadHandler284}285func (c compositeUploadHandler) OnUpload(ctx context.Context, args *UploadHandlerArgs) (Asset, *StorageError) {286 var err *StorageError287 for i := range c.Handlers {288 args.Asset, err = c.Handlers[i].OnUpload(ctx, args)289 if err != nil {290 return args.Asset, err291 }292 }293 return args.Asset, nil294}295// CompositeUploadHandler allows multiple upload handlers to be executed296func CompositeUploadHandler(handlers ...UploadHandler) UploadHandler {297 return compositeUploadHandler{Handlers: handlers}298}299// DeleteHandlerArgs represents arguments to the delete handler300type DeleteHandlerArgs struct {301 Request *http.Request302 Storage storage.Storage303 Kind string304 ID string305}306type compositeDeleteHandler struct {307 Handlers []DeleteHandler308}309func (c compositeDeleteHandler) OnDelete(ctx context.Context, args *DeleteHandlerArgs) *StorageError {...
upload
Using AI Code Generation
1import (2type SmartContract struct {3}4type Asset struct {5}6func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) peer.Response {7 return shim.Success(nil)8}9func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) peer.Response {10 function, args := APIstub.GetFunctionAndParameters()11 if function == "queryAsset" {12 return s.queryAsset(APIstub, args)13 } else if function == "initLedger" {14 return s.initLedger(APIstub)15 } else if function == "uploadAsset" {16 return s.uploadAsset(APIstub, args)17 } else if function == "queryAllAssets" {18 return s.queryAllAssets(APIstub)19 }20 return shim.Error("Invalid Smart Contract function name.")21}22func (s *SmartContract) queryAsset(APIstub shim.ChaincodeStubInterface, args []string) peer.Response {23 if len(args) != 1 {24 return shim.Error("Incorrect number of arguments. Expecting 1")25 }26 assetAsBytes, _ := APIstub.GetState(args[0])27 return shim.Success(assetAsBytes)28}29func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) peer.Response {30 assets := []Asset{31 Asset{AssetId: "1", AssetName: "Asus Laptop", AssetDesc: "Asus Laptop", AssetOwner: "Manoj", AssetStatus: "Active", AssetLocation: "Bangalore", AssetPrice: "10000"},32 Asset{AssetId: "2", AssetName: "Dell Laptop", AssetDesc: "Dell Laptop", AssetOwner: "Rahul", AssetStatus: "Active", Asset
upload
Using AI Code Generation
1import (2func main() {3 sess, err := session.New()4 if err != nil {5 log.Fatal(err)6 }7 resourceManagementAPI := management.New(sess)8 assetManagementAPI := asset.New(sess)9 resourceGroupQuery := management.ResourceGroupQuery{10 }11 resourceGroupList, err := resourceManagementAPI.ResourceGroup().List(&resourceGroupQuery)12 if err != nil {13 log.Fatal(err)14 }15 assetRepositoryQuery := asset.RepositoryQuery{16 }17 assetRepositoryList, err := assetManagementAPI.Repository().List(&assetRepositoryQuery)18 if err != nil {19 log.Fatal(err)20 }21 file, err := os.Open("test.txt")22 if err != nil {23 log.Fatal(err)24 }25 defer file.Close()26 fileName := filepath.Base(file.Name())27 fileExtension := filepath.Ext(file.Name())28 fileContentType := http.DetectContentType([]byte(fileExtension))29 fileInfo, err := file.Stat()30 if err != nil {31 log.Fatal(err)32 }33 fileContentLength := fileInfo.Size()34 assetOptions := asset.CreateAssetOptions{35 ContentLength: int64(fileContentLength),36 }37 asset, err := assetManagementAPI.Asset().Create(&assetOptions)38 if err != nil {39 log.Fatal(err)40 }
upload
Using AI Code Generation
1import (2func main() {3 sess, err := session.New()4 if err != nil {5 fmt.Println(err)6 }7 resourceManagementAPI := management.New(sess)8 assetManagementAPI := asset.New(sess)9 resourceGroupQuery := management.ResourceGroupQuery{10 }11 resourceGroupQuery.SetAccountFilter(os.Getenv("IC_ACCOUNT_ID"))12 resourceGroup, err := resourceManagementAPI.ResourceGroup().FindByName("default", resourceGroupQuery)13 if err != nil {14 fmt.Println(err)15 }16 account, err := resourceManagementAPI.Account().GetAccount()17 if err != nil {18 fmt.Println(err)19 }20 serviceInstanceQuery := management.ServiceInstanceQuery{21 }22 serviceInstanceQuery.SetAccountFilter(accountID)23 serviceInstance, err := resourceManagementAPI.ServiceInstance().FindByName("terraform-service", serviceInstanceQuery)24 if err != nil {25 fmt.Println(err)26 }27 assetQuery := asset.AssetQuery{28 }29 assetQuery.SetAccountFilter(accountID)30 asset, err := assetManagementAPI.Asset().FindByName("terraform-asset", assetQuery)31 if err != nil {32 fmt.Println(err)33 }
upload
Using AI Code Generation
1import (2func main() {3 asset1 := asset.Asset{Id: 1, Name: "asset1", Type: "image", Size: 10.0, Location: "location1"}4 asset2 := asset.Asset{Id: 2, Name: "asset2", Type: "image", Size: 10.0, Location: "location2"}5 asset3 := asset.Asset{Id: 3, Name: "asset3", Type: "image", Size: 10.0, Location: "location3"}6 asset4 := asset.Asset{Id: 4, Name: "asset4", Type: "image", Size: 10.0, Location: "location4"}7 asset5 := asset.Asset{Id: 5, Name: "asset5", Type: "image", Size: 10.0, Location: "location5"}8 asset6 := asset.Asset{Id: 6, Name: "asset6", Type: "image", Size: 10.0, Location: "location6"}9 asset7 := asset.Asset{Id: 7, Name: "asset7", Type: "image", Size: 10.0, Location: "location7"}10 asset8 := asset.Asset{Id: 8, Name: "asset8", Type: "image", Size: 10.0, Location: "location8"}11 asset9 := asset.Asset{Id: 9, Name: "asset9", Type: "image", Size: 10.0, Location: "location9"}12 asset10 := asset.Asset{Id: 10, Name: "asset10", Type: "image", Size: 10.0, Location: "location10"}
upload
Using AI Code Generation
1import (2type SmartContract struct {3}4type Asset struct {5}6type AssetDetails struct {7}8func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) peer.Response {9 return shim.Success(nil)10}11func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) peer.Response {12 function, args := APIstub.GetFunctionAndParameters()13 if function == "upload" {14 return s.upload(APIstub, args)15 } else if function == "query" {16 return s.query(APIstub, args)17 } else if function == "update" {18 return s.update(APIstub, args)19 }20 return shim.Error("Invalid Smart Contract function name.")21}22func (s *SmartContract) upload(APIstub shim.ChaincodeStubInterface, args []string) peer.Response {23 if len(args) != 4 {
upload
Using AI Code Generation
1asset := new(Asset)2asset.Upload()3asset := new(Asset)4asset.Delete()5asset := new(Asset)6asset.Get()7asset := new(Asset)8asset.List()9asset := new(Asset)10asset.Update()11asset := new(Asset)12asset.CreateFolder()13asset := new(Asset)14asset.DeleteFolder()15asset := new(Asset)16asset.ListFolder()17asset := new(Asset)18asset.GetFolder()19asset := new(Asset)20asset.UpdateFolder()21asset := new(Asset)22asset.GetAssetUrl()23asset := new(Asset)24asset.GetAssetUrl()25asset := new(Asset)26asset.GetAssetUrl()27asset := new(Asset)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!