beta.blog

Archive for August, 2025

Golang: Pure Go RAR file extracting

by on Aug.01, 2025, under News

The following code is a pure Go unrar implementation. It supports multi‑volume archives, compressed archives and takes a password (or empty string “” if no password is required). It was tested with RAR 6.x archives but supports older versions as well.

Also, during unpacking, the folder structure of the archive is retained.

package main

import (
	"io"
	"log"
	"os"
	"path/filepath"

	"github.com/nwaples/rardecode"
)

func extractRAR(srcDir, destDir, password string) error {
	rc, err := rardecode.OpenReader(srcDir, password)
	if err != nil {
		return err
	}
	defer rc.Close()

	rr := &rc.Reader
	for {
		hdr, err := rr.Next()
		if err == io.EOF {
			return nil
		} else if err != nil {
			return err
		}

		outPath := filepath.Join(destDir, hdr.Name)
		if hdr.IsDir {
			if err := os.MkdirAll(outPath, hdr.Mode()); err != nil {
				return err
			}
			continue
		}

		if err := os.MkdirAll(filepath.Dir(outPath), 0755); err != nil {
			return err
		}

		f, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, hdr.Mode())
		if err != nil {
			return err
		}
		if _, err := io.Copy(f, rr); err != nil {
			f.Close()
			return err
		}
		f.Close()
	}
}

func main() {
	if err := extractRAR("archive.rar", "./output", "mySecretPassword"); err != nil {
		log.Fatal(err)
	}
	log.Println("Done!")
}
Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!