gostruct

package module
v0.0.0-...-912581e Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2015 License: MIT Imports: 7 Imported by: 1

README

gostruct

GoDoc Build Status

gostruct populates Go structs from webpages using CSS selectors.

Install

go get github.com/bfontaine/gostruct

Usage

type MyStruct struct {
    Title string `gostruct:"#a-selector"`
    Desc  string `gostruct:"h1 .another .one"`
}

var ms MyStruct

gostruct.Fetch(&ms, "http://www.example.com")

gostruct supports all standard CSS selectors. Additionally, you can end a selector with /foo to get the foo attribute on the selected element. This works only on simple values (i.e. not on slices nor structs).

Example

The example program below searchs for "golang" on Google and prints the top results.

package main

import (
    "fmt"
    "os"

    "github.com/bfontaine/gostruct"
)

type Result struct {
    Title       string `gostruct:"h3.r"`
    Website     string `gostruct:".kv cite"`
    Description string `gostruct:".st"`
}

type Search struct {
    Results []Result `gostruct:"#search li.g"`
}

func main() {
    var s Search

    err := gostruct.Fetch(&s, "https://www.google.com/search?q=golang&hl=en")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        os.Exit(1)
    }

    for _, r := range s.Results {
        fmt.Printf("%s (%s) - %s\n", r.Title, r.Website, r.Description)
    }
}

Documentation

Overview

Package gostruct provides a simple API to populate structs from webpages using CSS selectors.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fetch

func Fetch(target interface{}, url string) error

Fetch fetches a document from an URL and populates the given target, which must be a pointer on a struct. See Populate for the details.

func Populate

func Populate(target interface{}, doc *goquery.Document) error

Populate fills a struct using the given goquery document. The target must be a pointer on a struct. Types are parsed as follow:

  • uint, int, float, duration, and string values are parsed from the first element which match the selector
  • bool values are true if the text from the selection is not empty
  • slice values are parsed with one slice element per element in the selection.

If a selector contains a slash, the part after it is assumed to be an attribute name. The attribute's value will then be used instead of the element's content.

func PopulateFromResponse

func PopulateFromResponse(target interface{}, res *http.Response) error

PopulateFromResponse fills a struct using the given HTTP response. See Populate for the details.

Types

This section is empty.

Jump to

Keyboard shortcuts

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