Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions comments/handler/comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ func (h *Handler) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.Cre
CreatedAt: now,
}

// Extract first URL and fetch link preview
url := extractFirstURL(req.Content)
if url != "" {
title, desc, image, err := fetchLinkPreview(url)
if err == nil {
comment.LinkPreview = &pb.LinkPreview{
Url: url,
Title: title,
Description: desc,
Image: image,
}
}
}

rsp.Comment = comment

// Save to store
Expand Down
61 changes: 61 additions & 0 deletions comments/handler/linkpreview.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package handler

import (
"net/http"
"regexp"
"strings"
"golang.org/x/net/html"
)

// Extracts the first URL from a string (simple regex)
func extractFirstURL(text string) string {
re := regexp.MustCompile(`https?://[^\s]+`)
match := re.FindString(text)
return match
}

// Fetches Open Graph/meta tags from a URL
func fetchLinkPreview(url string) (title, description, image string, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
z := html.NewTokenizer(resp.Body)
for {
tt := z.Next()
switch tt {
case html.ErrorToken:
return // End of document
case html.StartTagToken, html.SelfClosingTagToken:
t := z.Token()
if t.Data == "meta" {
var property, content string
for _, a := range t.Attr {
if a.Key == "property" || a.Key == "name" {
property = a.Val
}
if a.Key == "content" {
content = a.Val
}
}
if property == "og:title" && title == "" {
title = content
}
if property == "og:description" && description == "" {
description = content
}
if property == "og:image" && image == "" {
image = content
}
if property == "description" && description == "" {
description = content
}
}
if t.Data == "title" && title == "" {
z.Next()
title = strings.TrimSpace(z.Token().Data)
}
}
}
}
Loading