Security
Go มี features หลายอย่างที่ช่วยให้เขียนโค้ดปลอดภัย แต่ก็ต้องระวังหลายจุด
Input Validation
Section titled “Input Validation”package main
import ( "fmt" "regexp" "strings" "unicode")
func validateUsername(username string) error { if len(username) < 3 || len(username) > 20 { return fmt.Errorf("username must be 3-20 characters") }
// ต้องเริ่มด้วยตัวอักษร if !unicode.IsLetter(rune(username[0])) { return fmt.Errorf("username must start with a letter") }
// ยอมรับเฉพาะ alphanumeric และ underscore validRe := regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`) if !validRe.MatchString(username) { return fmt.Errorf("username contains invalid characters") }
return nil}
func validateEmail(email string) error { emailRe := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`) if !emailRe.MatchString(email) { return fmt.Errorf("invalid email format") } return nil}
func main() { tests := []string{"admin", "user_123", "a", "admin@domain", "<script>"}
for _, u := range tests { err := validateUsername(u) if err != nil { fmt.Printf("%s: INVALID - %v\n", u, err) } else { fmt.Printf("%s: VALID\n", u) } }}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google