HOWTO · Go

GoLang 이메일 검사기

이 튜토리얼은 Go에서 이메일을 검증하는 방법을 보여줍니다.

이 튜토리얼은 GoLang에서 이메일을 검증하는 방법을 보여줍니다.

이메일에는 특정 형식이 필요합니다. 그렇지 않으면 작동하지 않습니다. 그렇기 때문에 이메일 시스템을 구축할 때 이메일 유효성 검사가 중요합니다. 이 튜토리얼은 GoLang에서 이메일을 검증하는 다양한 방법을 보여줍니다.

Regex를 사용하여 GoLang 이메일 검사기 만들기

정규식은 다양한 프로그래밍 언어에 대한 다양한 형식의 유효성을 검사하는 데 사용됩니다. GoLang은 또한 다양한 형식의 유효성을 검사하고 이메일 유효성 검사에 사용할 수 있는 regexp 패키지를 제공합니다.

예를 들어 보겠습니다.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    string1 := "delftstack.123@hotmail.com"
    string2 := "demo@delftstack.com"
    string3 := "demo@delftstack.tv"
    string4 := "demohotmail.com"
    string5 := "demo@"

    // regex pattern for email ^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$
    RegexPattern := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")

    fmt.Printf("Email 1: %v :%v\n", string1, RegexPattern.MatchString(string1))
    fmt.Printf("Email 2: %v :%v\n", string2, RegexPattern.MatchString(string2))
    fmt.Printf("Email 3: %v :%v\n", string3, RegexPattern.MatchString(string3))
    fmt.Printf("Email 4: %v :%v\n", string4, RegexPattern.MatchString(string4))
    fmt.Printf("Email 5: %v :%v\n", string5, RegexPattern.MatchString(string5))
    fmt.Printf("\nThe regex email pattern: %v\n", RegexPattern.String())

}

위의 코드는 Go 언어의 regexp 패키지를 사용하는 정규식을 기반으로 이메일의 유효성을 검사합니다. 위 코드의 출력을 참조하십시오.

Email 1: delftstack.123@hotmail.com :true
Email 2: demo@delftstack.com :true
Email 3: demo@delftstack.tv :true
Email 4: demohotmail.com :false
Email 5: demo@ :false

The regex email pattern: ^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$

Mail API를 사용하여 GoLang 이메일 검사기 만들기

GoLang의 mail API에는 이메일 유효성 검사에 사용되는 mail.ParseAddress 메서드가 있습니다. 이 함수는 RFC 5322 주소를 구문 분석하고 name <local-part@domain> 형식을 사용하여 문자열이 이메일인지 확인할 수도 있습니다.

mail.ParseAddress 메서드를 사용하여 이메일 유효성 검사기를 구현하는 방법을 살펴보겠습니다.

package main

import (
    "fmt"
    "net/mail"
)

func EmailValidator(EmailAddress string) (string, bool) {
    a, b := mail.ParseAddress(EmailAddress)
    if b != nil {
        return "", false
    }
    return a.Address, true
}

var EmailAddresses = []string{
    "delftstack.123@hotmail.com",
    "Delftstack <demo@delftstack.com>",
    "demo@delftstack.tv",
    "demohotmail.com",
    "demo@",
}

func main() {
    for _, e_address := range EmailAddresses {
        if emailaddress, ok := EmailValidator(e_address); ok {
            fmt.Printf("The Input: %-30s Valadity: %-10t Email Address: %s\n", e_address, ok, emailaddress)
        } else {
            fmt.Printf("The Input: %-30s Valadity: %-10t\n", e_address, ok)
        }
    }
}

위의 코드는 mail.ParseAddress 메소드를 사용하여 EmailValidator 기능을 생성합니다. 이 코드는 이메일 배열의 유효성 검사를 확인합니다.

출력을 참조하십시오.

The Input: delftstack.123@hotmail.com     Valadity: true       Email Address: delftstack.123@hotmail.com
The Input: Delftstack <demo@delftstack.com> Valadity: true       Email Address: demo@delftstack.com
The Input: demo@delftstack.tv             Valadity: true       Email Address: demo@delftstack.tv
The Input: demohotmail.com                Valadity: false
The Input: demo@                          Valadity: false

GoLang 이메일 검사기용 방법 만들기

정규식을 찾기 어렵거나 패키지를 로드하는 데 모호성이 있다고 가정합니다. 이 경우 GoLang 코드를 기반으로 메서드를 생성하여 표준 형식을 기반으로 이메일을 검증할 수도 있습니다.

다음은 예입니다.

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func EmailValidator(emailaddress string) bool {
    if emailaddress == "" {
        return false
    }
    if CheckSpace(emailaddress) {
        return false
    }

    AttheRate := strings.IndexByte(emailaddress, '@')
    if AttheRate == -1 {
        return false
    }

    localPart := emailaddress[:AttheRate]
    if localPart == "" {
        return false
    }

    DomainCheck := emailaddress[AttheRate+1:]
    if DomainCheck == "" {
        return false
    }

    LastDot := strings.IndexByte(DomainCheck, '.')
    if LastDot == -1 || LastDot == 0 || LastDot == len(DomainCheck)-1 {
        return false
    }

    if strings.Index(DomainCheck, "..") != -1 {
        return false
    }

    AfterDot := strings.LastIndexByte(DomainCheck, '.')
    return 2 <= len([]rune(DomainCheck[AfterDot+1:]))
}

func CheckSpace(emailaddress string) bool {
    for _, a := range emailaddress {
        if unicode.IsSpace(a) {
            return true
        }
    }
    return false
}

func main() {
    string1 := "delftstack.123@hotmail.com"
    string2 := "demo@delftstack.com"
    string3 := "demo@delftstack.tv"
    string4 := "demohotmail.com"
    string5 := "demo@"

    fmt.Printf("Email 1: %v :%v\n", string1, EmailValidator(string1))
    fmt.Printf("Email 2: %v :%v\n", string2, EmailValidator(string2))
    fmt.Printf("Email 3: %v :%v\n", string3, EmailValidator(string3))
    fmt.Printf("Email 4: %v :%v\n", string4, EmailValidator(string4))
    fmt.Printf("Email 5: %v :%v\n", string5, EmailValidator(string5))

}

위의 코드는 전자 메일 유효성 검사를 확인하기 위해 GoLang 코드를 기반으로 하는 메서드를 생성합니다. 출력을 보자:

Email 1: delftstack.123@hotmail.com :true
Email 2: demo@delftstack.com :true
Email 3: demo@delftstack.tv :true
Email 4: demohotmail.com :false
Email 5: demo@ :false