go-security
Skill9 starsChanged 8 months agoMITView on GitHub
Use when writing, reviewing, or auditing Go code for security. Covers input validation, SQL injection prevention, path traversal, secrets management, cryptography, HTTP security headers, and dependency scanning.
- Installs packages
1 other project uses a version of this.
Adopted by
Most recently taken up by
- Dankosik/golang-backend-skillstheir own version, first seen Sep 8, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- Dankosik/golang-backend-skills★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository8 other files it gives its agents.
- golangSkill
- go-code-reviewSkill
- go-concurrencySkill
- go-error-handlingSkill
- go-lintingSkill
- go-performanceSkill
- go-project-layoutSkill
- go-testingSkill
The file
We split this skill into the rules it gives an agent
11 rules. About 0 are common, 6 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 21
Always use parameterized queries.
- Very specific: line 38
Use os.Root for scoped file access.
- Very specific: line 57
Use filepath.Clean and verify the result stays within the intended directory:
- Distinctive: line 102
Never hardcode secrets. Never log them.
- Very specific: line 119
Use type Secret string with a custom String() method to prevent accidental logging:
- Distinctive: line 134
Use the standard library. Do not implement your own crypto.
- Distinctive: line 150
Use bcrypt or argon2. Never store passwords as plaintext or simple hashes.
- Distinctive: line 166
Always set timeouts on HTTP servers and clients.
- Distinctive: line 209
Keep dependencies up to date and scan for known vulnerabilities:
- Very specific: line 221
Run govulncheck in CI. It checks your code against the Go vulnerability database and only reports vulnerabilities in functions you actually …
- Very specific: line 231
Always run tests with -race in CI.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Go Security
Secure coding patterns for production Go. Covers OWASP top risks as they apply to Go.
SQL Injection Prevention
Always use parameterized queries. Never interpolate user input into SQL strings.
// Wrong: SQL injection
query := "SELECT * FROM users WHERE id = '" + id + "'"
db.Query(query)
// Correct: parameterized query
db.QueryContext(ctx, "SELECT * FROM users WHERE id = $1", id)This applies to all database drivers. The placeholder syntax varies ($1 for postgres, ? for mysql).
Path Traversal Prevention
os.Root (Go 1.24+)
Use os.Root for scoped file access. Paths are resolved within the root directory and cannot escape it.
root, err := os.OpenRoot("/var/data/uploads")
if err != nil {
return err
}
defer root.Close()
// Safe: "../etc/passwd" is rejected
f, err := root.Open(userProvidedFilename)
if err != nil {
return err
}
defer f.Close()Pre-Go 1.24
Use filepath.Clean and verify the result stays within the intended directory:
cleaned := filepath.Clean(userInput)
absPath := filepath.Join(baseDir, cleaned)
// Verify the path is still under baseDir
if !strings.HasPrefix(absPath, filepath.Clean(baseDir)+string(os.PathSeparator)) {
return fmt.Errorf("path traversal: %s", userInput)
}Input Validation
Validate all external input at system boundaries. Internal code can trust validated data.
func parseUserID(raw string) (int64, error) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid user ID %q: %w", raw, err)
}
if id <= 0 {
return 0, fmt.Errorf("user ID must be positive, got %d", id)
}
return id, nil
}For structured input, decode into typed structs and validate fields:
var req CreateUserRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
if err := req.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}Secrets Management
Never hardcode secrets. Never log them.
// Wrong: secret in source code
const apiKey = "do-not-hardcode-secrets"
// Wrong: secret in error message or log
slog.Info("connecting", "dsn", os.Getenv("DATABASE_URL"))
// Correct: read from environment, treat as opaque
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
return errors.New("DATABASE_URL is required")
}
slog.Info("connecting to database") // no secret in logUse type Secret string with a custom String() method to prevent accidental logging:
type Secret string
func (s Secret) String() string { return "[REDACTED]" }
func (s Secret) GoString() string { return "[REDACTED]" }
// The actual value is accessible via explicit conversion
dsn := string(cfg.DatabaseURL)Cryptography
Use the standard library. Do not implement your own crypto.
import "crypto/rand"
// Generate random bytes (for tokens, nonces)
token := make([]byte, 32)
if _, err := rand.Read(token); err != nil {
return err
}
// Do NOT use math/rand for security-sensitive valuesPassword Hashing
Use bcrypt or argon2. Never store passwords as plaintext or simple hashes.
import "golang.org/x/crypto/bcrypt"
// Hash a password
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
// Verify a password
err := bcrypt.CompareHashAndPassword(hash, []byte(password))HTTP Security
Timeouts
Always set timeouts on HTTP servers and clients. Default zero value means no timeout.
srv := &http.Server{
Addr: ":8080",
Handler: handler,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
client := &http.Client{
Timeout: 10 * time.Second,
}Response Headers
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Content-Security-Policy", "default-src 'self'")
next.ServeHTTP(w, r)
})
}Close Response Bodies
Unclosed HTTP response bodies leak connections:
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()Dependency Scanning
Keep dependencies up to date and scan for known vulnerabilities:
# Check for known vulnerabilities (built into Go)
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
# Update all dependencies
go get -u ./...
go mod tidyRun govulncheck in CI. It checks your code against the Go vulnerability database and only reports vulnerabilities in functions you actually call.
Concurrency Safety
Shared mutable state without synchronization is a data race and a security risk. Use the race detector in tests:
go test -race ./...Always run tests with -race in CI. Data races can cause memory corruption, which in certain contexts is exploitable.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

