Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang get domain from email using parse standard library

Tags:

parsing

go

I'm having trouble pulling out the domain for emails. I've tried using variations of

u, _ := url.Parse(email) 

and other parsing from the standard library, but nothing that seems to parse: [email protected] into separate parts.

I've also tried net.SplitHostPort with no luck.

I don't want to get create a function which gets the len and separate to get substring after @ symbol if possible.

Does anyone have any ideas to do this?

Thanks!

like image 888
jj1111 Avatar asked Feb 15 '17 18:02

jj1111


1 Answers

Here's an example I concocted from the golang documentation:

package main

import (
    "fmt"
    "strings"
)

func main() {
    email := "[email protected]"
    components := strings.Split(email, "@")
    username, domain := components[0], components[1]
    
    fmt.Printf("Username: %s, Domain: %s\n", username, domain)
}

UPDATE: 2020-09-01 - updating to use last @ sign per @Kevin's feedback in the comments.

package main

import (
    "fmt"
    "strings"
)

func main() {
    email := "[email protected]"
    at := strings.LastIndex(email, "@")
    if at >= 0 {
        username, domain := email[:at], email[at+1:]

        fmt.Printf("Username: %s, Domain: %s\n", username, domain)
    } else {
        fmt.Printf("Error: %s is an invalid email address\n", email)
    }
}

Here are some tests: https://play.golang.org/p/cg4RqZADLml

like image 145
Mohamed Nuur Avatar answered Nov 15 '22 10:11

Mohamed Nuur