Build a Go dependency scanner with the standard library: parse go.mod, query OSV for vulnerabilities, and analyze licenses.Build a Go dependency scanner with the standard library: parse go.mod, query OSV for vulnerabilities, and analyze licenses.

Building a Go Dependency Scanner From Scratch

When managing Go projects, you need to track dependencies, check for vulnerabilities, and ensure license compliance. Instead of relying on external tools, let's build our own dependency analyzer using Go's standard library.

\

The Core Structure

We'll work with Go modules, so we need structures to represent them:

package main  import (     "bufio"     "encoding/json"     "fmt"     "io"     "net/http"     "os"     "regexp"     "sort"     "strings"     "time" )  type Module struct {     Path     string     Version  string     Indirect bool }  type GoMod struct {     Module   Module     Requires []Module } 

\ Our tool will handle three operations: listing dependencies, vulnerability scanning, and license checking.

\

Parsing go.mod Files

Understanding Module File Structure

The go.mod file uses a specific format that we need to parse correctly. Module declarations start with the module keyword followed by the module path. Dependencies are listed in require statements, which can be single-line or grouped in multi-line blocks.

\ The parsing logic handles both formats by tracking whether we're inside a multi-line require block. We use regular expressions to extract the module path and version from each line, and detect indirect dependencies by looking for the // indirect comment. This approach gives us the same information that go list would provide, but without spawning external processes.

\ Rather than shelling out to go list, we can parse the go.mod file directly:

func parseGoMod() (*GoMod, error) {     file, err := os.Open("go.mod")     if err != nil {         return nil, fmt.Errorf("go.mod not found: %v", err)     }     defer file.Close()      goMod := &GoMod{         Requires: []Module{},     }      scanner := bufio.NewScanner(file)     inRequire := false     requireRegex := regexp.MustCompile(`^\s*([^\s]+)\s+([^\s]+)(?:\s+//\s*indirect)?`)     moduleRegex := regexp.MustCompile(`^module\s+(.+)`)      for scanner.Scan() {         line := strings.TrimSpace(scanner.Text())          if strings.HasPrefix(line, "module ") {             if matches := moduleRegex.FindStringSubmatch(line); len(matches) > 1 {                 goMod.Module = Module{Path: matches[1]}             }         }          if strings.HasPrefix(line, "require (") {             inRequire = true             continue         }          if inRequire && line == ")" {             inRequire = false             continue         }          if inRequire || strings.HasPrefix(line, "require ") {             cleanLine := strings.TrimPrefix(line, "require ")             if matches := requireRegex.FindStringSubmatch(cleanLine); len(matches) >= 3 {                 module := Module{                     Path:     matches[1],                     Version:  matches[2],                     Indirect: strings.Contains(line, "indirect"),                 }                 goMod.Requires = append(goMod.Requires, module)             }         }     }      return goMod, scanner.Err() } 

\ The parser handles both single-line requires and multi-line require blocks. It extracts module paths, versions, and identifies indirect dependencies.

\

Vulnerability Database Queries

How Vulnerability Checking Works

Vulnerability databases maintain records of known security issues in software packages. Each vulnerability gets assigned identifiers like CVE numbers and includes details about affected versions. The process works like this: we send the package name and version to the database API, it checks if that specific version has any known vulnerabilities, then returns a list of issues if found.

\ The OSV database is particularly useful because it aggregates vulnerability data from multiple sources and provides a unified API. When we query it, we're essentially asking "does this exact version of this package have any reported security problems?" The database performs version matching and returns structured data about any findings.

\ We can check the OSV (Open Source Vulnerabilities) database for known issues:

func checkOSVDatabase(modulePath, version string) []string {     url := "https://api.osv.dev/v1/query"      payload := map[string]interface{}{         "package": map[string]string{             "name":      modulePath,             "ecosystem": "Go",         },         "version": version,     }      jsonData, err := json.Marshal(payload)     if err != nil {         return []string{}     }      client := &http.Client{Timeout: 10 * time.Second}     resp, err := client.Post(url, "application/json", strings.NewReader(string(jsonData)))     if err != nil {         return []string{}     }     defer resp.Body.Close()      if resp.StatusCode != 200 {         return []string{}     }      var result struct {         Vulns []struct {             ID      string `json:"id"`             Summary string `json:"summary"`         } `json:"vulns"`     }      if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {         return []string{}     }      var vulnerabilities []string     for _, vuln := range result.Vulns {         vulnStr := fmt.Sprintf("%s: %s", vuln.ID, vuln.Summary)         vulnerabilities = append(vulnerabilities, vulnStr)     }      return vulnerabilities }  func checkVulnerabilities() {     goMod, err := parseGoMod()     if err != nil {         fmt.Printf("Error: %v\n", err)         return     }      vulnerableModules := 0      for i, mod := range goMod.Requires {         fmt.Printf("\rScanning %d/%d: %s", i+1, len(goMod.Requires), mod.Path)         vulns := checkOSVDatabase(mod.Path, mod.Version)         if len(vulns) > 0 {             vulnerableModules++             fmt.Printf("\n🚨 %s@%s:\n", mod.Path, mod.Version)             for _, vuln := range vulns {                 fmt.Printf("  - %s\n", vuln)             }         }     }      if vulnerableModules == 0 {         fmt.Println("\n✅ No known vulnerabilities found")     } else {         fmt.Printf("\n⚠️ Found %d vulnerable modules\n", vulnerableModules)     } } 

\ The vulnerability checker sends a JSON payload with the module name and version, then parses the response for any reported vulnerabilities.

\

License Information Fetching

How License Detection Works

License compliance checking involves identifying what legal terms govern each dependency in your project. Most open source projects include license files in their repositories, and platforms like GitHub parse these files to identify the license type using SPDX identifiers.

\ Our approach leverages GitHub's license detection API, which analyzes repository contents and returns standardized license identifiers. For modules hosted on GitHub, we extract the owner and repository name from the module path, then query GitHub's API endpoint that specifically provides license information. This gives us machine-readable license data without having to download and parse license files ourselves.

\ Different licenses have different requirements , some like MIT are very permissive, while others like GPL have copyleft requirements that might affect how you can distribute your software. Understanding these differences is crucial for legal compliance.

\ For GitHub-hosted modules, we can get license data from their API:

func fetchGitHubLicense(owner, repo string) string {     url := fmt.Sprintf("https://api.github.com/repos/%s/%s/license", owner, repo)      client := &http.Client{Timeout: 10 * time.Second}     resp, err := client.Get(url)     if err != nil {         return "Unknown"     }     defer resp.Body.Close()      if resp.StatusCode != 200 {         return "Unknown"     }      var result struct {         License struct {             SPDXID string `json:"spdx_id"`         } `json:"license"`     }      if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {         return "Unknown"     }      if result.License.SPDXID != "" && result.License.SPDXID != "NOASSERTION" {         return result.License.SPDXID     }      return "Unknown" }  func fetchLicenseFromRepo(modulePath string) string {     if strings.HasPrefix(modulePath, "golang.org/x/") {         return "BSD-3-Clause"     }      if !strings.HasPrefix(modulePath, "github.com/") {         return "Unknown"     }      parts := strings.Split(modulePath, "/")     if len(parts) < 3 {         return "Unknown"     }      return fetchGitHubLicense(parts[1], parts[2]) }  func checkLicenses() {     goMod, err := parseGoMod()     if err != nil {         fmt.Printf("Error: %v\n", err)         return     }      licenseCount := make(map[string]int)      for i, mod := range goMod.Requires {         fmt.Printf("\rProcessing %d/%d...", i+1, len(goMod.Requires))         license := fetchLicenseFromRepo(mod.Path)         licenseCount[license]++         fmt.Printf("\r  %s: %s\n", mod.Path, license)     }      fmt.Println("\nLicense Distribution:")     for license, count := range licenseCount {         percentage := float64(count) / float64(len(goMod.Requires)) * 100         fmt.Printf("  %s: %d modules (%.1f%%)\n", license, count, percentage)     } } 

\ The license checker recognizes that golang.org/x/ packages use BSD-3-Clause, then queries GitHub's API for other repositories.

\

Dependency Analysis with Checksum Verification

The dependency analyzer lists modules and verifies their integrity using go.sum:

func parseGoSum() map[string]string {     checksums := make(map[string]string)      file, err := os.Open("go.sum")     if err != nil {         return checksums     }     defer file.Close()      scanner := bufio.NewScanner(file)     for scanner.Scan() {         parts := strings.Fields(scanner.Text())         if len(parts) >= 3 {             module := parts[0] + "@" + parts[1]             checksums[module] = parts[2]         }     }      return checksums }  func analyzeDependencies() {     goMod, err := parseGoMod()     if err != nil {         fmt.Printf("Error: %v\n", err)         return     }      checksums := parseGoSum()      fmt.Printf("Module: %s\n", goMod.Module.Path)     fmt.Printf("Found %d dependencies:\n\n", len(goMod.Requires))      direct, indirect := 0, 0      sort.Slice(goMod.Requires, func(i, j int) bool {         return goMod.Requires[i].Path < goMod.Requires[j].Path     })      for _, mod := range goMod.Requires {         status := "direct"         if mod.Indirect {             status = "indirect"             indirect++         } else {             direct++         }          checksumKey := mod.Path + "@" + mod.Version         hasChecksum := "❌"         if _, exists := checksums[checksumKey]; exists {             hasChecksum = "✅"         }          fmt.Printf("  %s %s@%s (%s)\n", hasChecksum, mod.Path, mod.Version, status)     }      fmt.Printf("\nSummary: %d direct, %d indirect dependencies\n", direct, indirect) } 

\

Command Interface

The main function routes commands to the appropriate handlers:

func main() {     if len(os.Args) < 2 {         fmt.Println("Usage: go run main.go <command>")         fmt.Println("Commands:")         fmt.Println("  deps      List all dependencies")         fmt.Println("  vulns     Check for vulnerabilities")         fmt.Println("  licenses  Check license compliance")         os.Exit(1)     }      switch os.Args[1] {     case "deps":         analyzeDependencies()     case "vulns":         checkVulnerabilities()     case "licenses":         checkLicenses()     default:         fmt.Println("Unknown command")         os.Exit(1)     } } 

\

Running the Tool

Save the code as main.go and run it in any Go project:

# List dependencies with checksum verification go run main.go deps 

\

# Scan for vulnerabilities go run main.go vulns 

\

\

# Analyze licenses go run main.go licenses 

\

\ The output shows dependency information, vulnerability reports, and license distribution across your project's dependencies. The tool demonstrates how dependency analysis works behind the scenes, parsing module files, querying public APIs, and cross-referencing data sources.

\ This implementation covers the basic concepts but is just a starting point. Real vulnerability scanning requires comprehensive databases, sophisticated version range matching, false positive filtering, and robust error handling. License compliance tools need legal policy engines, compatibility matrices, and custom license detection beyond what GitHub's API provides. For production use, you'd want multiple data sources, caching, rate limiting, and much more thorough validation logic.

\ Happy coding ;)

\ You can find source code here https://github.com/rezmoss/go-dependency-scanner

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Husky Inu (HINU) Completes Move To $0.00020688

Husky Inu (HINU) Completes Move To $0.00020688

Husky Inu (HINU) has completed its latest price jump, rising from $0.00020628 to $0.00020688. The price jump is part of the project’s pre-launch phase, which began on April 1, 2025.
Share
Cryptodaily2025/09/18 01:10
US Senate Releases Draft Crypto Bill Establishing Clear Regulatory Framework for Digital Assets

US Senate Releases Draft Crypto Bill Establishing Clear Regulatory Framework for Digital Assets

TLDR: Bill resolves SEC-CFTC conflict by assigning clear regulatory authority over securities and commodities respectively. Ancillary assets category exempts network
Share
Blockonomi2026/01/14 04:57
Unprecedented Surge: Gold Price Hits Astounding New Record High

Unprecedented Surge: Gold Price Hits Astounding New Record High

BitcoinWorld Unprecedented Surge: Gold Price Hits Astounding New Record High While the world often buzzes with the latest movements in Bitcoin and altcoins, a traditional asset has quietly but powerfully commanded attention: gold. This week, the gold price has once again made headlines, touching an astounding new record high of $3,704 per ounce. This significant milestone reminds investors, both traditional and those deep in the crypto space, of gold’s enduring appeal as a store of value and a hedge against uncertainty. What’s Driving the Record Gold Price Surge? The recent ascent of the gold price to unprecedented levels is not a random event. Several powerful macroeconomic forces are converging, creating a perfect storm for the precious metal. Geopolitical Tensions: Escalating conflicts and global instability often drive investors towards safe-haven assets. Gold, with its long history of retaining value during crises, becomes a preferred choice. Inflation Concerns: Persistent inflation in major economies erodes the purchasing power of fiat currencies. Consequently, investors seek assets like gold that historically maintain their value against rising prices. Central Bank Policies: Many central banks globally are accumulating gold at a significant pace. This institutional demand provides a strong underlying support for the gold price. Furthermore, expectations around interest rate cuts in the future also make non-yielding assets like gold more attractive. These factors collectively paint a picture of a cautious market, where investors are looking for stability amidst a turbulent economic landscape. Understanding Gold’s Appeal in Today’s Market For centuries, gold has held a unique position in the financial world. Its latest record-breaking performance reinforces its status as a critical component of a diversified portfolio. Gold offers a tangible asset that is not subject to the same digital vulnerabilities or regulatory shifts that can impact cryptocurrencies. While digital assets offer exciting growth potential, gold provides a foundational stability that appeals to a broad spectrum of investors. Moreover, the finite supply of gold, much like Bitcoin’s capped supply, contributes to its perceived value. The current market environment, characterized by economic uncertainty and fluctuating currency values, only amplifies gold’s intrinsic benefits. It serves as a reliable hedge when other asset classes, including stocks and sometimes even crypto, face downward pressure. How Does This Record Gold Price Impact Investors? A soaring gold price naturally raises questions for investors. For those who already hold gold, this represents a significant validation of their investment strategy. For others, it might spark renewed interest in this ancient asset. Benefits for Investors: Portfolio Diversification: Gold often moves independently of other asset classes, offering crucial diversification benefits. Wealth Preservation: It acts as a robust store of value, protecting wealth against inflation and economic downturns. Liquidity: Gold markets are highly liquid, allowing for relatively easy buying and selling. Challenges and Considerations: Opportunity Cost: Investing in gold means capital is not allocated to potentially higher-growth assets like equities or certain cryptocurrencies. Volatility: While often seen as stable, gold prices can still experience significant fluctuations, as evidenced by its rapid ascent. Considering the current financial climate, understanding gold’s role can help refine your overall investment approach. Looking Ahead: The Future of the Gold Price What does the future hold for the gold price? While no one can predict market movements with absolute certainty, current trends and expert analyses offer some insights. Continued geopolitical instability and persistent inflationary pressures could sustain demand for gold. Furthermore, if global central banks continue their gold acquisition spree, this could provide a floor for prices. However, a significant easing of inflation or a de-escalation of global conflicts might reduce some of the immediate upward pressure. Investors should remain vigilant, observing global economic indicators and geopolitical developments closely. The ongoing dialogue between traditional finance and the emerging digital asset space also plays a role. As more investors become comfortable with both gold and cryptocurrencies, a nuanced understanding of how these assets complement each other will be crucial for navigating future market cycles. The recent surge in the gold price to a new record high of $3,704 per ounce underscores its enduring significance in the global financial landscape. It serves as a powerful reminder of gold’s role as a safe haven asset, a hedge against inflation, and a vital component for portfolio diversification. While digital assets continue to innovate and capture headlines, gold’s consistent performance during times of uncertainty highlights its timeless value. Whether you are a seasoned investor or new to the market, understanding the drivers behind gold’s ascent is crucial for making informed financial decisions in an ever-evolving world. Frequently Asked Questions (FAQs) Q1: What does a record-high gold price signify for the broader economy? A record-high gold price often indicates underlying economic uncertainty, inflation concerns, and geopolitical instability. Investors tend to flock to gold as a safe haven when they lose confidence in traditional currencies or other asset classes. Q2: How does gold compare to cryptocurrencies as a safe-haven asset? Both gold and some cryptocurrencies (like Bitcoin) are often considered safe havens. Gold has a centuries-long history of retaining value during crises, offering tangibility. Cryptocurrencies, while newer, offer decentralization and can be less susceptible to traditional financial system failures, but they also carry higher volatility and regulatory risks. Q3: Should I invest in gold now that its price is at a record high? Investing at a record high requires careful consideration. While the price might continue to climb due to ongoing market conditions, there’s also a risk of a correction. It’s crucial to assess your personal financial goals, risk tolerance, and consider diversifying your portfolio rather than putting all your capital into a single asset. Q4: What are the main factors that influence the gold price? The gold price is primarily influenced by global economic uncertainty, inflation rates, interest rate policies by central banks, the strength of the U.S. dollar, and geopolitical tensions. Demand from jewelers and industrial uses also play a role, but investment and central bank demand are often the biggest drivers. Q5: Is gold still a good hedge against inflation? Historically, gold has proven to be an effective hedge against inflation. When the purchasing power of fiat currencies declines, gold tends to hold its value or even increase, making it an attractive asset for preserving wealth during inflationary periods. To learn more about the latest crypto market trends, explore our article on key developments shaping Bitcoin’s price action. This post Unprecedented Surge: Gold Price Hits Astounding New Record High first appeared on BitcoinWorld.
Share
Coinstats2025/09/18 02:30