A Go library to parse and format vCard

go-vcard

GoDoc Build Status codecov

A Go library to parse and format vCard.

Usage

f, err := os.Open("cards.vcf")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

dec := vcard.NewDecoder(f)
for {
	card, err := dec.Decode()
	if err == io.EOF {
		break
	} else if err != nil {
		log.Fatal(err)
	}

	log.Println(card.PreferredValue(vcard.FieldFormattedName))
}

License

MIT

Owner
Simon Ser
I work on open-source software.
Simon Ser
Comments
  • GetAllFields

    GetAllFields

    I would love to access all Fields, so far you only can Get one(the preferred) value by calling Get. You have access to all the Values, but that might not be sufficient: In my case, I want to have the details on all existing phone Numbers, so whether that phoneNumber is for Work, Home, Cell, etc.

    So my simple suggestion:

    // GetAllFields returns all fields of the card for the given property. If there is    
    // no such field, it returns nil.  
    func (c Card) GetAllFields(k string) []*Field {  
    	fields := c[k]  
    	if len(fields) == 0 {  
    		return nil  
    	}  
    	return fields  
    }
    

    and on that you can extract all necessary information. Or is there a better way to extract all phone Numbers with the details on them?

  • Parse Field.Value not possible with vcard 2.1 format parameters

    Parse Field.Value not possible with vcard 2.1 format parameters

    When trying to test processing a vcf file exported using thunderbird, we encounter empty value for some fields, like email.

    The vcard format is 2.1 and it appear that parameters are not encoded as key=value tuples as in format 3.0 and 4.0 they are. This make parseParam function of decoder.go parsing the Field.Value as a parameter value.

    Example of format not parsed correctly :

    begin:vcard
    fn:someone
    email;internet:[email protected]
    version:2.1
    end:vcard
    

    Using this temporary solution I get back Field.Value filled correctly , but bypass completly any parameters:

    https://gist.github.com/gdchamal/43c58f9d581cee05c40706692f852373

    Yes I know vcard2.1 format should not exist anymore ;)

    What do you think ?

  • Decode and Encode to string

    Decode and Encode to string

    I've this string

    Hasan Yousef
    BEGIN:VCARD
    VERSION:3.0
    N:Yousef;Hasan;;;
    FN:Hasan Yousef
    item1.TEL;waid=966xxxxxxxxx:+966 xx xxx xxxx
    item1.X-ABLabel:Mobile
    END:VCARD
    
    1. How can I convert the above string to to vcard.Card, i.e. Encode string into vCard
    2. If I have the vcard.Card how can I convert it into string, i.e. Decode a vCard into string
  • example error

    example error

    example error:

    
    func main() {
    	destFile, err := os.Create(".\Contacts2.vcf")
    	if err != nil {
    		log.Fatal(err)
    	}
    	defer destFile.Close()
    
    	// data in order: first name, middle name, last name, telephone number
    	contacts := [][4]string{
    		{"John", "Webber", "Maxwell", "(+1) 199 8714"},
    		{"Donald", "", "Ron", "(+44) 421 8913"},
    		{"Eric", "E.", "Peter", "(+37) 221 9903"},
    		{"Nelson", "D.", "Patrick", "(+1) 122 8810"},
    	}
    
    	var (
    		// card is a map of strings to []*vcard.Field objects
    		card vcard.Card
    
    		// destination where the vcard will be encoded to
    		enc = vcard.NewEncoder(destFile)
    	)
    
    	for _, entry := range contacts {
    		// set only the value of a field by using card.SetValue.
    		// This does not set parameters
    		card.SetValue(vcard.FieldFormattedName, strings.Join(entry[:3], " "))
    		card.SetValue(vcard.FieldTelephone, entry[3])
    
    		// set the value of a field and other parameters by using card.Set
    		card.Set(vcard.FieldName, &vcard.Field{
    			Value: strings.Join(entry[:3], ";"),
    			Params: map[string][]string{
    				vcard.ParamSortAs: []string{
    					entry[0] + " " + entry[2],
    				},
    			},
    		})
    
    		// make the vCard version 4 compliant
    		vcard.ToV4(card)
    		err := enc.Encode(card)
    		if err != nil {
    			log.Fatal(err)
    		}
    	}
    }
    
    

    panic: assignment to entry in nil map

    goroutine 1 [running]:
    github.com/emersion/go-vcard.Card.Set(...)
    D:/gopath/src/github.com/emersion/go-vcard/card.go:118
    github.com/emersion/go-vcard.Card.SetValue(...)
    D:/gopath/src/github.com/emersion/go-vcard/card.go:166
    main.main()
    /vcard_cretor2.go:110 +0x3cd

  • How can I convert enc to string

    How can I convert enc to string

    I wrote the below that created vcard, but once I tried to read the vcard back to its string I failed:

    package main
    
    import (
    	"io"
    	"log"
    	"strings"
    
    	"github.com/emersion/go-vcard"
    )
    
    func main() {
    
    	var content strings.Builder
    	content.WriteString("BEGIN:VCARD\n")
    	content.WriteString("VERSION:3.0\n")
    	content.WriteString("FN:Hasan Yousef\n")
    	content.WriteString("TEL:999\n")
    	content.WriteString("Fitem1.TEL;waid=966000000000\n")
    	content.WriteString("item1.X-ABLabel:Mobile\n")
    	content.WriteString("END:VCARD")
    
    	r := strings.NewReader(content.String())
    	dec := vcard.NewDecoder(r)
    	var card vcard.Card
    	var err error
    	for {
    		card, err = dec.Decode()
    		if err == io.EOF {
    			break
    		} else if err != nil {
    			log.Fatal(err)
    		}
    
    		log.Println(card.PreferredValue(vcard.FieldFormattedName))
    		log.Println(card.PreferredValue(vcard.FieldTelephone))
    	}
    
    	var enc vcard.Encoder
    
    	// enc = vcard.NewEncoder(destFile)
    	err = enc.Encode(card)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// How can I convert enc to string!
    
    	log.Println(&enc)
    
    }
    

    I got:

    2022/05/07 12:44:47 Hasan Yousef
    2022/05/07 12:44:47 999
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal 0xc0000005 code=0x0 addr=0x18 pc=0x10549d]
    
    goroutine 1 [running]:
    io.WriteString({0x0, 0x0}, {0x15c770, 0xd})
            D:/Development/go/src/io/io.go:314 +0x7d
    github.com/emersion/go-vcard.(*Encoder).Encode(0xc00004a360, 0x3?)
            D:/Development/gopath/pkg/mod/github.com/emersion/[email protected]/encoder.go:23 +0x57
    main.main()
            D:/Desktop/main.go:41 +0x77e
    exit status 2
    
  • Reading telephone number

    Reading telephone number

    I noticed telephone number is defined as TEL https://github.com/emersion/go-vcard/blob/dd3110a24ec26a6b9f8a45da21cc0f2ca2ce8c67/card.go#L53 And can be read as:

    log.Println(card.PreferredValue(vcard.FieldTelephone))
    

    But in my vcard, telephone number is defined as:

    Fitem1.TEL;waid=966000000000
    

    How can I read it?

  • invalid BEGIN value

    invalid BEGIN value

    I tried:

    package main
    
    import (
    	"io"
    	"log"
    	"strings"
    
    	"github.com/emersion/go-vcard"
    )
    
    func main() {
    
    	var content strings.Builder
    	content.WriteString("BEGIN:VCARD")
    	content.WriteString("VERSION:3.0")
    	content.WriteString("FN:Hasan Yousef")
    	content.WriteString("Fitem1.TEL;waid=966000000000")
    	content.WriteString("item1.X-ABLabel:Mobile")
    	content.WriteString("END:VCARD")
    
    	//	byteData := bytes.Buffer{}
    	//	byteData.Write([]byte(content.String()))
    	//	dec := vcard.Decoder(buf)
    	//	r := bytes.NewReader([]byte(content.String()))
    
    	r := strings.NewReader(content.String())
    	dec := vcard.NewDecoder(r)
    	for {
    		card, err := dec.Decode()
    		if err == io.EOF {
    			break
    		} else if err != nil {
    			log.Fatal(err)
    		}
    
    		log.Println(card.PreferredValue(vcard.FieldFormattedName))
    	}
    }
    

    But got:

    2022/05/07 10:18:24 vcard: invalid BEGIN value
    exit status 1
    

    Once I tried commenting it:

    //	content.WriteString("BEGIN:VCARD")
    

    I got:

    2022/05/07 10:21:31 vcard: no BEGIN field found
    
  • Add cards and save cards example

    Add cards and save cards example

    Thanks for the library, I was able to see my contacts. Since, I am new to golang, and just wanted to see if it is possible that you provide a way to add a new contact and save all contacts in documentation.

  • fix: Preferred() returns field with highest PREF

    fix: Preferred() returns field with highest PREF

    According to https://tools.ietf.org/html/rfc6350#section-5.3:

    Its value MUST be an integer between 1 and 100 that quantifies the level of preference. Lower values correspond to a higher level of preference, with 1 being most preferred.

Pagser is a simple, extensible, configurable parse and deserialize html page to struct based on goquery and struct tags for golang crawler
Pagser is a simple, extensible, configurable parse and deserialize html page to struct based on goquery and struct tags for golang crawler

Pagser Pagser inspired by page parser。 Pagser is a simple, extensible, configurable parse and deserialize html page to struct based on goquery and str

Dec 13, 2022
Parse data and test fixtures from markdown files, and patch them programmatically, too.

go-testmark Do you need test fixtures and example data for your project, in a language agnostic way? Do you want it to be easy to combine with documen

Oct 31, 2022
Parse placeholder and wildcard text commands

allot allot is a small Golang library to match and parse commands with pre-defined strings. For example use allot to define a list of commands your CL

Nov 24, 2022
Parse RSS, Atom and JSON feeds in Go
Parse RSS, Atom and JSON feeds in Go

gofeed The gofeed library is a robust feed parser that supports parsing both RSS, Atom and JSON feeds. The library provides a universal gofeed.Parser

Jan 8, 2023
parse and generate XML easily in go

etree The etree package is a lightweight, pure go package that expresses XML in the form of an element tree. Its design was inspired by the Python Ele

Dec 19, 2022
Parse line as shell words

go-shellwords Parse line as shell words. Usage args, err := shellwords.Parse("./foo --bar=baz") // args should be ["./foo", "--bar=baz"] envs, args, e

Dec 23, 2022
Extraction politique de conformité : xlsx (fichier de suivi) -> xml (format AlgoSec)

go_policyExtractor Extraction politique de conformité : xlsx (fichier de suivi) -> xml (format AlgoSec). Le programme suivant se base sur les intitulé

Nov 4, 2021
wikipedia-jsonl is a CLI that converts Wikipedia dump XML to JSON Lines format.

wikipedia-jsonl wikipedia-jsonl is a CLI that converts Wikipedia dump XML to JSON Lines format. How to use At first, download the XML dump from Wikime

Dec 26, 2022
A general purpose application and library for aligning text.

align A general purpose application that aligns text The focus of this application is to provide a fast, efficient, and useful tool for aligning text.

Sep 27, 2022
omniparser: a native Golang ETL streaming parser and transform library for CSV, JSON, XML, EDI, text, etc.
omniparser: a native Golang ETL streaming parser and transform library for CSV, JSON, XML, EDI, text, etc.

omniparser Omniparser is a native Golang ETL parser that ingests input data of various formats (CSV, txt, fixed length/width, XML, EDI/X12/EDIFACT, JS

Jan 4, 2023
:book: A Golang library for text processing, including tokenization, part-of-speech tagging, and named-entity extraction.

prose prose is a natural language processing library (English only, at the moment) in pure Go. It supports tokenization, segmentation, part-of-speech

Jan 4, 2023
👄 The most accurate natural language detection library in the Go ecosystem, suitable for long and short text alike
👄 The most accurate natural language detection library in the Go ecosystem, suitable for long and short text alike

?? The most accurate natural language detection library in the Go ecosystem, suitable for long and short text alike

Dec 25, 2022
yview is a lightweight, minimalist and idiomatic template library based on golang html/template for building Go web application.

wview wview is a lightweight, minimalist and idiomatic template library based on golang html/template for building Go web application. Contents Instal

Dec 5, 2021
A NMEA parser library in pure Go

go-nmea This is a NMEA library for the Go programming language (Golang). Features Parse individual NMEA 0183 sentences Support for sentences with NMEA

Dec 20, 2022
Go library for the TOML language

go-toml Go library for the TOML format. This library supports TOML version v1.0.0-rc.3 Features Go-toml provides the following features for using data

Dec 27, 2022
A declarative struct-tag-based HTML unmarshaling or scraping package for Go built on top of the goquery library

goq Example import ( "log" "net/http" "astuart.co/goq" ) // Structured representation for github file name table type example struct { Title str

Dec 12, 2022
The Go library for working with delimited separated value (DSV).

Package dsv is a Go library for working with delimited separated value (DSV). NOTE: This package has been deprecated. See https://github.com/shuLhan/s

Sep 15, 2021
Upskirt markdown library bindings for Go

Goskirt Package goskirt provides Go-bindings for the excellent Sundown Markdown parser. (F/K/A Upskirt). To use goskirt, create a new Goskirt-value wi

Oct 23, 2022
Golang HTML to plaintext conversion library

html2text Converts HTML into text of the markdown-flavored variety Introduction Ensure your emails are readable by all! Turns HTML into raw text, usef

Dec 28, 2022