Created
July 31, 2017 12:04
-
-
Save buddax2/1cf5c47acd285777547070a6c7644525 to your computer and use it in GitHub Desktop.
Get url preview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"net/http" | |
"strings" | |
"io/ioutil" | |
"github.com/gin-gonic/gin" | |
"github.com/dyatlov/go-opengraph/opengraph" | |
) | |
type Preview struct { | |
Url string `json:"url"` | |
Title string `json:"title"` | |
Description string `json:"description"` | |
Images []*opengraph.Image `json:"images"` | |
} | |
func getPreview_v2(c *gin.Context) { | |
htmlURL := c.Query("url") | |
resp, err := http.Get(htmlURL) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} else { | |
defer resp.Body.Close() | |
html, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
fmt.Println(err) | |
panic(err) | |
} | |
og := opengraph.NewOpenGraph() | |
ogErr := og.ProcessHTML(strings.NewReader(fmt.Sprintf("%s", html))) | |
if ogErr != nil { | |
fmt.Println(ogErr) | |
return | |
} else { | |
preview := Preview{Url: og.URL, Title:og.Title, Description:og.Description, Images:og.Images} | |
c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "data" : preview}) | |
} | |
} | |
} | |
func main() { | |
port := os.Getenv("PORT") | |
if port == "" { | |
log.Fatal("$PORT must be set") | |
} | |
router := gin.New() | |
router.Use(gin.Logger()) | |
router.GET("/", getPreview_v2) | |
router.Run(":" + port) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment