handler.go (1531B)
1 // Copyright 2023 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package govulncheck 6 7 import ( 8 "encoding/json" 9 "io" 10 11 "golang.org/x/vuln/internal/osv" 12 ) 13 14 // Handler handles messages to be presented in a vulnerability scan output 15 // stream. 16 type Handler interface { 17 // Config communicates introductory message to the user. 18 Config(config *Config) error 19 20 // SBOM shows information about what govulncheck is scanning. 21 SBOM(sbom *SBOM) error 22 23 // Progress is called to display a progress message. 24 Progress(progress *Progress) error 25 26 // OSV is invoked for each osv Entry in the stream. 27 OSV(entry *osv.Entry) error 28 29 // Finding is called for each vulnerability finding in the stream. 30 Finding(finding *Finding) error 31 } 32 33 // HandleJSON reads the json from the supplied stream and hands the decoded 34 // output to the handler. 35 func HandleJSON(from io.Reader, to Handler) error { 36 dec := json.NewDecoder(from) 37 for dec.More() { 38 msg := Message{} 39 // decode the next message in the stream 40 if err := dec.Decode(&msg); err != nil { 41 return err 42 } 43 // dispatch the message 44 var err error 45 if msg.Config != nil { 46 err = to.Config(msg.Config) 47 } 48 if msg.Progress != nil { 49 err = to.Progress(msg.Progress) 50 } 51 if msg.SBOM != nil { 52 err = to.SBOM(msg.SBOM) 53 } 54 if msg.OSV != nil { 55 err = to.OSV(msg.OSV) 56 } 57 if msg.Finding != nil { 58 err = to.Finding(msg.Finding) 59 } 60 if err != nil { 61 return err 62 } 63 } 64 return nil 65 }