Skip to content

Instantly share code, notes, and snippets.

@bxcodec
Forked from techslides/golang-prettyurl.go
Created August 7, 2017 03:35
Show Gist options
  • Save bxcodec/0a472bd4c87c40ae673a11f7884714e8 to your computer and use it in GitHub Desktop.
Save bxcodec/0a472bd4c87c40ae673a11f7884714e8 to your computer and use it in GitHub Desktop.
Generating Pretty Urls for SEO in GoLang using string and regex packages
type Post struct {
// db tag lets you specify the column name if it differs from the struct field
Id int64 `db:"post_id"`
Created int64
Title string `form:"Title" binding:"required"`
Body string `form:"Body"`
UserId int64 `form:"UserId"`
Url string
}
//function to create a new Post object
func newPost(title string, body string, user int64) Post {
//let's make pretty urls from title
reg, err := regexp.Compile("[^A-Za-z0-9]+")
if err != nil {
log.Fatal(err)
}
prettyurl := reg.ReplaceAllString(title, "-")
prettyurl = strings.ToLower(strings.Trim(prettyurl, "-"))
return Post{
Created: time.Now().Unix(),
Title: title,
Body: body,
UserId: user,
Url: prettyurl,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment