Skip to content

Instantly share code, notes, and snippets.

@svelleweetakealot
Created June 12, 2017 20:55
Show Gist options
  • Save svelleweetakealot/952e80c1480206312113e320eebbdbd5 to your computer and use it in GitHub Desktop.
Save svelleweetakealot/952e80c1480206312113e320eebbdbd5 to your computer and use it in GitHub Desktop.
xslt lib example in go
package main
/*
#cgo pkg-config: libxslt
#include <string.h>
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/DOCBparser.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
static void usage(const char *name) {
printf("Usage: %s [options] stylesheet file [file ...]\n", name);
printf(" --param name value : pass a (parameter,value) pair\n");
}
extern int xmlLoadExtDtdDefaultValue;
static void init(const char* stylesheet, const char* document) {
xsltStylesheetPtr cur = NULL;
xmlDocPtr doc, res;
xmlSubstituteEntitiesDefault(1);
xmlLoadExtDtdDefaultValue = 1;
cur = xsltParseStylesheetFile((const xmlChar*) stylesheet);
doc = xmlParseFile(document);
res = xsltApplyStylesheet(cur, doc, NULL);
xsltSaveResultToFile(stdout, res, cur);
xsltFreeStylesheet(cur);
xmlFreeDoc(res);
xmlFreeDoc(doc);
xsltCleanupGlobals();
xmlCleanupParser();
}
*/
import "C"
import (
"os"
)
func main() {
if len(os.Args) < 3 {
C.usage(C.CString(os.Args[0]))
}
C.init(C.CString(os.Args[1]), C.CString(os.Args[2]))
}
@Demitroi
Copy link

Demitroi commented Apr 17, 2020

I'd problems to build in ubuntu. I solved by installing the next packages.

sudo apt-get update
sudo apt-get install pkg-config
sudo apt-get install libxslt-dev

When it built prompts the next warning

$ go build -v
_/home/sergio/pruebas/cgo-xslt
# _/home/sergio/pruebas/cgo-xslt
In file included from ./cgo-xslt.go:10:0:
/usr/include/libxml2/libxml/DOCBparser.h:22:2: warning: #warning "The DOCBparser module has been deprecated in libxml2-2.6.0" [-Wcpp]
 #warning "The DOCBparser module has been deprecated in libxml2-2.6.0"
  ^~~~~~~

Deleting line 10 there were no warnings

#include <libxml/DOCBparser.h>

There was a panic when it run without args

$ ./cgo-xslt
Usage: ./cgo-xslt [options] stylesheet file [file ...]
      --param name value : pass a (parameter,value) pair
panic: runtime error: index out of range [1] with length 1

goroutine 1 [running]:
main.main()
        /home/sergio/pruebas/cgo-xslt/cgo-xslt.go:53 +0xf8

Just added a return after usage

func main() {
	if len(os.Args) < 3 {
		C.usage(C.CString(os.Args[0]))
		return
	}
	C.init(C.CString(os.Args[1]), C.CString(os.Args[2]))	
}

I ran a example with xsltproc to compare the result an was the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment