httpzip

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2025 License: MIT Imports: 12 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httpzip

Build Status Coverage Status GoDevDoc Time Tracker Code lines Comments

Serve multiple files in uncompressed ZIP stream (no temporary archive file) with progress (Content-Length header) status.

h := httpzip.NewHandler("archive")
h.OnError = func(err error) {
    log.Println(err)
}

c := "hello world"

for i := 0; i < 10; i++ {
    if err := h.AddFile(httpzip.FileSource{
        Path:     fmt.Sprintf("file_%d.txt", i),
        Modified: time.Now(),
        Size:     int64(len(c)),
        Data: func(w io.Writer) error {
            _, err := w.Write([]byte(c)) // Mimicking actual file source.

            return err
        },
    }); err != nil {
        log.Println(err)
    }
}

h.ServeHTTP(rw, nil)

Extract ZIP file directly (no temporary archive file) from a URL.

resp, err := http.Get("https://www.example.com/archive.zip")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

zr := httpzip.NewStreamReader(resp.Body)

for {
    e, err := zr.Next()
    if err == io.EOF {
        break
    }

    if err != nil {
        log.Fatalf("failed to find next file in zip: %s", err)
    }

    log.Println("file path:", e.Name)

    if !e.IsDir() {
        rc, err := e.Open()
        if err != nil {
            log.Fatalf("unable to open zip file entry: %s", err)
        }

        w, err := io.Copy(io.Discard, rc)
        if err != nil {
            log.Fatalf("unable to stream zip file: %s (%d)", err, w)
        }

        log.Println("file length:", w)

        if err := rc.Close(); err != nil {
            log.Fatalf("failed to close zip file entry: %s", err)
        }
    }
}

Documentation

Overview

Package httpzip provides a HTTP handler to serve multiple files in a ZIP stream.

Index

Examples

Constants

View Source
const (
	Zip64ExtraID       = 0x0001 // Zip64 extended information.
	NtfsExtraID        = 0x000a // NTFS.
	UnixExtraID        = 0x000d // UNIX.
	ExtTimeExtraID     = 0x5455 // Extended timestamp.
	InfoZipUnixExtraID = 0x5855 // Info-ZIP Unix extension.
)

Extra header IDs. See http://mdfs.net/Docs/Comp/Archiving/Zip/ExtraField.

Variables

This section is empty.

Functions

This section is empty.

Types

type Entry added in v0.1.1

type Entry struct {
	zip.FileHeader
	// contains filtered or unexported fields
}

Entry represents a file or directory in ZIP archive.

func (*Entry) IsDir added in v0.1.1

func (e *Entry) IsDir() bool

IsDir returns true for directories.

func (*Entry) Open added in v0.1.1

func (e *Entry) Open() (io.ReadCloser, error)

Open opens entry contents for reading.

type FileSource

type FileSource struct {
	Path     string
	Modified time.Time
	Size     int64
	CRC32    uint32 // CRC32 checksum of the file content, optional.
	Data     func(w io.Writer) error
}

FileSource describes archive entry.

func (*FileSource) FillCRC32 added in v0.1.2

func (fs *FileSource) FillCRC32() error

FillCRC32 counts CRC32 if it is empty.

type Handler

type Handler struct {
	OnError     func(err error)
	Streamable  bool // Use inlined raw file headers instead of final directory to allow streaming decoding.
	IgnoreCRC32 bool // Allow streamable ZIP with empty CRC32.
	// contains filtered or unexported fields
}

Handler serves multiple files in uncompressed ZIP.

func NewHandler

func NewHandler(archiveName string) *Handler

NewHandler creates an instance of Handler.

Example
package main

import (
	"fmt"
	"io"
	"log"
	"net/http/httptest"
	"time"

	"github.com/vearutop/httpzip"
)

func main() {
	rw := httptest.NewRecorder()

	h := httpzip.NewHandler("archive")
	h.Streamable = true
	h.OnError = func(err error) {
		log.Println(err)
	}

	c := "hello world"

	for i := 0; i < 10; i++ {
		if err := h.AddFile(httpzip.FileSource{
			Path:     fmt.Sprintf("file_%d.txt", i),
			Modified: time.Now(),
			Size:     int64(len(c)),
			Data: func(w io.Writer) error {
				_, err := w.Write([]byte(c)) // Mimicking actual file source.

				return err
			},
		}); err != nil {
			log.Println(err)
		}
	}

	h.ServeHTTP(rw, nil)

	fmt.Println("Status:", rw.Code)
	fmt.Println("Content-Length:", rw.Header().Get("Content-Length"))

}
Output:
Status: 200
Content-Length: 1092

func (*Handler) AddFile

func (h *Handler) AddFile(fs FileSource) error

AddFile add a file to the archive.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(rw http.ResponseWriter, _ *http.Request)

type StreamReader added in v0.1.1

type StreamReader struct {
	// contains filtered or unexported fields
}

StreamReader can read ZIP contents from a io.Reader.

func NewStreamReader added in v0.1.1

func NewStreamReader(r io.Reader) *StreamReader

NewStreamReader returns streaming ZIP reader.

Example
package main

import (
	"io"
	"log"
	"net/http"

	"github.com/vearutop/httpzip"
)

func main() {
	resp, err := http.Get("https://www.example.com/archive.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	zr := httpzip.NewStreamReader(resp.Body)

	for {
		e, err := zr.Next()
		if err == io.EOF {
			break
		}

		if err != nil {
			log.Fatalf("failed to find next file in zip: %s", err)
		}

		log.Println("file path:", e.Name)

		if !e.IsDir() {
			rc, err := e.Open()
			if err != nil {
				log.Fatalf("unable to open zip file entry: %s", err)
			}

			w, err := io.Copy(io.Discard, rc)
			if err != nil {
				log.Fatalf("unable to stream zip file: %s (%d)", err, w)
			}

			log.Println("file length:", w)

			if err := rc.Close(); err != nil {
				log.Fatalf("failed to close zip file entry: %s", err)
			}
		}
	}
}

func (*StreamReader) Next added in v0.1.1

func (z *StreamReader) Next() (*Entry, error)

Next returns the next Entry.

Jump to

Keyboard shortcuts

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