Go FarmHash Code Example (Online Runner)

Go FarmHash64 examples with decimal output and file hashing to match the FarmHash tools.

Online calculator: use the site FarmHash text tool.

Note: This snippet requires locally installed dependencies and will not run in the online runner. Run it locally with: go mod init farmhash-demo && go get github.com/leemcloughlin/gofarmhash && go run farmhash_basic.go

Calculation method

FarmHash fingerprint returns a 64-bit integer. The tool displays the unsigned decimal value.

Implementation notes

  • Package: github.com/leemcloughlin/gofarmhash.
  • Implementation: output is formatted as an unsigned base-10 string.
  • Notes: FarmHash is not cryptographic.

Text hashing example

go
package main

import (
	"fmt"
	"strconv"

	gofarmhash "github.com/leemcloughlin/gofarmhash"
)

func farmHash64Text(text string) string {
	value := gofarmhash.Hash64([]byte(text))
	return strconv.FormatUint(value, 10)
}

func main() {
	fmt.Println(farmHash64Text("hello"))
}

File hashing example

go
package main

import (
	"fmt"
	"os"
	"strconv"

	gofarmhash "github.com/leemcloughlin/gofarmhash"
)

func farmHash64File(path string) (string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return "", err
	}
	value := gofarmhash.Hash64(data)
	return strconv.FormatUint(value, 10), nil
}

func main() {
	file, err := os.CreateTemp("", "farmhash-example-*.bin")
	if err != nil {
		panic(err)
	}
	defer os.Remove(file.Name())
	file.WriteString("hello")
	file.Close()

	value, err := farmHash64File(file.Name())
	if err != nil {
		panic(err)
	}
	fmt.Println(value)
}

Complete script (implementation + tests)

go
package main

import (
	"fmt"
	"os"
	"strconv"

	gofarmhash "github.com/leemcloughlin/gofarmhash"
)

func farmHash64Text(text string) string {
	value := gofarmhash.Hash64([]byte(text))
	return strconv.FormatUint(value, 10)
}

func farmHash64File(path string) (string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return "", err
	}
	value := gofarmhash.Hash64(data)
	return strconv.FormatUint(value, 10), nil
}

func main() {
	fmt.Println("farmhash64=", farmHash64Text("hello"))

	file, err := os.CreateTemp("", "farmhash-example-*.bin")
	if err != nil {
		panic(err)
	}
	defer os.Remove(file.Name())
	file.WriteString("hello")
	file.Close()

	fileHash, err := farmHash64File(file.Name())
	if err != nil {
		panic(err)
	}
	fmt.Println("farmhash64(file)=", fileHash)
}