xiaochang 4 years ago
parent
commit
379d62726b
4 changed files with 59 additions and 8 deletions
  1. 1 1
      lib/shorturl/shorturl.go
  2. 40 0
      web/api/loadUrl.go
  3. 17 7
      web/api/shortUrl.go
  4. 1 0
      web/server.go

+ 1 - 1
lib/shorturl/shorturl.go

@@ -110,7 +110,7 @@ func (shorter *shorter) Expand(shortURL string) (longURL string, err error) {
 }
 func (shorter *shorter) GetSequence()(seq uint64, err error){
 	seq, err = shorter.sequence.NextSequence()
-	return seq,nil
+	return seq,err
 }
 func (shorter *shorter) Short(longURL string) (shortURL string, err error) {
 	for {

+ 40 - 0
web/api/loadUrl.go

@@ -0,0 +1,40 @@
+package api
+
+import (
+	"github.com/PuerkitoBio/goquery"
+	"github.com/gin-gonic/gin"
+	"log"
+	"net/http"
+)
+func LoadUrl(c *gin.Context){
+	url,_ := c.GetQuery("url")
+	res, err := http.Get(url)
+
+	if err != nil {
+		log.Print(err)
+		c.JSON(200, gin.H{
+			"err": err.Error(),
+		})
+	}else{
+		defer res.Body.Close()
+		if res.StatusCode != 200 {
+			log.Print("status code error: %d %s", res.StatusCode, res.Status)
+		}
+
+		// Load the HTML document
+		doc, err := goquery.NewDocumentFromReader(res.Body)
+		if err != nil {
+			log.Print(err)
+		}
+		title := doc.Find("title").Text()
+		description,_ :=doc.Find("meta[name=\"description\"]").Attr("content")
+		img,_:= doc.Find("img").First().Attr("src")
+		c.JSON(200, gin.H{
+			"title": title,
+			"description": description,
+			"img":img,
+		})
+	}
+
+
+}

+ 17 - 7
web/api/shortUrl.go

@@ -7,14 +7,24 @@ import (
 )
 
 func Redirect(c *gin.Context){
+	sid := c.Params.ByName("sid")
+	sq, err := shorturl.Shorter.GetSequence()
+	if err != nil {
+		c.JSON(200, gin.H{
+			"message": lib.String2Int(sid),
+			"sequence": lib.Int2String(sq),
+			"sequence_id": sq,
+			"error": err,
+		})
+	} else {
+		c.JSON(200, gin.H{
+			"message": lib.String2Int(sid),
+			"sequence": lib.Int2String(sq),
+			"sequence_id": sq,
+		})
+	}
 
 }
 func Short(c *gin.Context){
-	sid := c.Params.ByName("sid")
-	sq, _ := shorturl.Shorter.GetSequence()
-	c.JSON(200, gin.H{
-		"message": lib.String2Int(sid),
-		"sequence": lib.Int2String(sq),
-		"sequence_id": sq,
-	})
+
 }

+ 1 - 0
web/server.go

@@ -15,6 +15,7 @@ func Start() {
 	})
 	r.GET("/ver", api.CheckVersion)
 	r.GET("/health", api.CheckHealth)
+	r.GET("/load", api.LoadUrl)
 	r.GET("/u:sid", api.Redirect)