googp

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 30, 2022 License: Apache-2.0 Imports: 13 Imported by: 0

README

googp

CircleCI Go Report Card PkgGoDev

googp is an OGP (Open Graph protocol) parser library for Golang.

Overviews

  • 💯 Fully compliant with the reference
  • 🔧 Highly customizable
    • Available your own structs
    • Available parsing your own OG Tags.
  • 🙌 Supports type conversion

Installation

To install it, run:

go get -u github.com/soranoba/googp

Usage

import (
    "fmt"
    "github.com/soranoba/googp"
)

type Music struct {
}

type CustomOGP struct {
    Title       string   `googp:"og:title"`
    Description string   `googp:"-"`        // ignored
    images      []string                    // private field (ignored)
    Videos      []string `googp:"og:video,og:video:url"`
    Musics      Music    `googp:"music"`    // object type
}

func main() {
    var ogp1 googp.OGP
    if err := googp.Fetch("https://soranoba.net", &ogp1); err != nil {
        return
    }
    fmt.Println(ogp1)

    var ogp2 CustomOGP
    if err := googp.Fetch("https://soranoba.net", &ogp2); err != nil {
        return
    }
    fmt.Println(ogp2)
}

Object Mappings

Structured Properties
type OGP struct {
    Image struct {
        URL       string `googp:"og:image,og:image:url"`
        SecureURL string `googp:"og:image:secure_url"`
    } `googp:"og:image"`
}

You may collect in a struct by specifying the root tag.
In case of specifying og:image, googp collect values which property is og:image:*.

Arrays
type OGP struct {
    Image []string `googp:"og:image"`
}

googp collects values which the same properties.

Object Types

In googp, it same as Structured Properties.
You may define your own type yourself.

Documentation

Overview

Package googp is a OGP (Open Graph protocol) parser library for Golang.

This library is fully compliant with the reference, highly customizable, and supports type conversion.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsupportedPage is an unsupported page errror.
	ErrUnsupportedPage = errors.New("Unsupported page")
)

Functions

func Fetch

func Fetch(rawurl string, i interface{}, opts ...ParserOpts) error

Fetch the content from the URL and parse OGP information.

Example
var ogp OGP
if err := Fetch(endpoint()+"/5.html", &ogp); err != nil {
	return
}

fmt.Printf("og:title = \"%s\"\n", ogp.Title)
fmt.Printf("og:type = \"%s\"\n", ogp.Type)
fmt.Printf("og:url = \"%s\"\n", ogp.URL)
Output:

og:title = "Open Graph protocol"
og:type = "website"
og:url = "https://ogp.me/"
Example (CustomizeModel)
// URL is embedded url.URL and is added TextUnmarshaler implementation.
var _ encoding.TextUnmarshaler = &URL{}

type MyOGP struct {
	Title    string `googp:"og:title"`
	URL      URL    `googp:"og:url"`
	ImageURL *URL   `googp:"og:image"`
	AppID    int    `googp:"fb:app_id"`
}

var ogp MyOGP
if err := Fetch(endpoint()+"/5.html", &ogp); err != nil {
	return
}

fmt.Printf("og:title = \"%s\"\n", ogp.Title)
fmt.Printf("og:url = \"%s\"\n", ogp.URL.String())
fmt.Printf("og:image = \"%s\"\n", ogp.ImageURL.String())
fmt.Printf("fb:app_id = %d\n", ogp.AppID)
Output:

og:title = "Open Graph protocol"
og:url = "https://ogp.me/"
og:image = "https://ogp.me/logo.png"
fb:app_id = 115190258555800

func Parse added in v0.5.0

func Parse(res *http.Response, i interface{}, opts ...ParserOpts) error

Parse OGP information. It returns an error when the status code of the response is error.

Types

type Audio

type Audio struct {
	URL       string `googp:"og:audio,og:audio:url" json:"url,omitempty"`
	SecureURL string `googp:"og:audio:secure_url"   json:"secure_url,omitempty"`
	Type      string `googp:"og:audio:type"         json:"type,omitempty"`
}

Audio is a model that structure contents of og:audio.

type BadStatusCodeError added in v0.4.0

type BadStatusCodeError struct {
	StatusCode int
}

BadStatusCodeError is an error returned when the status code is not 200 in Fetch.

func (BadStatusCodeError) Error added in v0.4.0

func (err BadStatusCodeError) Error() string

type Image

type Image struct {
	URL       string `googp:"og:image,og:image:url" json:"url,omitempty"`
	SecureURL string `googp:"og:image:secure_url"   json:"secure_url,omitempty"`
	Type      string `googp:"og:image:type"         json:"type,omitempty"`
	Width     int    `googp:"og:image:width"        json:"width,omitempty"`
	Height    int    `googp:"og:image:height"       json:"height,omitempty"`
	Alt       string `googp:"og:image:alt"          json:"alt,omitempty"`
}

Image is a model that structure contents of og:image.

type Meta

type Meta struct {
	Property string
	Content  string
}

Meta is a model that structure contents of meta tag in html.

type OGP

type OGP struct {
	Title  string  `googp:"og:title" json:"title,omitempty"`
	Type   string  `googp:"og:type"  json:"type,omitempty"`
	URL    string  `googp:"og:url"   json:"url,omitempty"`
	Images []Image `googp:"og:image" json:"images,omitempty"`

	Audios          []Audio  `googp:"og:audio"            json:"audios,omitempty"`
	Description     string   `googp:"og:description"      json:"description,omitempty"`
	Determiner      string   `googp:"og:determiner"       json:"determiner,omitempty"`
	Locale          string   `googp:"og:locale"           json:"locale,omitempty"`
	LocaleAlternate []string `googp:"og:locale:alternate" json:"locale_alternate,omitempty"`
	SiteName        string   `googp:"og:site_name"        json:"site_name,omitempty"`
	Videos          []Video  `googp:"og:video"            json:"videos,omitempty"`
}

OGP is a model that have Basic Metadata and Optional Metadata defined in the reference. ref: https://ogp.me/

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser is an OGP parser.

func NewParser

func NewParser(opts ...ParserOpts) *Parser

NewParser create a `Parser`

func (*Parser) Parse

func (parser *Parser) Parse(reader io.Reader, i interface{}) error

Parse OGPs from the HTML.

Example
reader := strings.NewReader(`
		<html>
			<head>
				<meta property="og:title" content="title" />
				<meta property="og:type" content="website" />
				<meta property="og:url" content="http://example.com" />
				<meta property="og:image" content="http://example.com/image.png" />
			</head>
			<body>
			</body>
		</html>
	`)

var ogp OGP
if err := NewParser().Parse(reader, &ogp); err != nil {
	return
}

fmt.Printf("og:title = \"%s\"\n", ogp.Title)
fmt.Printf("og:type = \"%s\"\n", ogp.Type)
fmt.Printf("og:url = \"%s\"\n", ogp.URL)
fmt.Printf("og:image = \"%s\"\n", ogp.Images[0].URL)
Output:

og:title = "title"
og:type = "website"
og:url = "http://example.com"
og:image = "http://example.com/image.png"

func (*Parser) ParseNode

func (parser *Parser) ParseNode(n *html.Node, i interface{}) error

ParseNode is execute to parse OGPs from the HTML node.

type ParserOpts

type ParserOpts struct {
	// You can add processing when you need to regard another Nodes as `<meta>`.
	// For example, you can use it when you want to get the `<title>`.
	PreNodeFunc func(*html.Node) *Meta
	// You can add body to parse target.
	// If html have some meta tags in the body, you should set to true.
	IncludeBody bool
}

ParserOpts is an option of Parser.

type Video

type Video struct {
	URL       string `googp:"og:video,og:video:url" json:"url,omitempty"`
	SecureURL string `googp:"og:video:secure_url"   json:"secure_url,omitempty"`
	Type      string `googp:"og:video:type"         json:"type,omitempty"`
	Width     int    `googp:"og:video:width"        json:"width,omitempty"`
	Height    int    `googp:"og:video:height"       json:"height,omitempty"`
}

Video is a model that structure contents of og:video.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL