statik

Embed files into a Go executable

Github星跟蹤圖

statik

Build Status

statik allows you to embed a directory of static files into your Go binary to be later served from an http.FileSystem.

Is this a crazy idea? No, not necessarily. If you're building a tool that has a Web component, you typically want to serve some images, CSS and JavaScript. You like the comfort of distributing a single binary, so you don't want to mess with deploying them elsewhere. If your static files are not large in size and will be browsed by a few people, statik is a solution you are looking for.

Usage

Install the command line tool first.

go get github.com/rakyll/statik

statik is a tiny program that reads a directory and generates a source file that contains its contents. The generated source file registers the directory contents to be used by statik file system.

The command below will walk on the public path and generate a package called statik under the current working directory.

$ statik -src=/path/to/your/project/public

The command below will filter only files on listed extensions.

$ statik -include=*.jpg,*.txt,*.html,*.css,*.js

In your program, all your need to do is to import the generated package, initialize a new statik file system and serve.

import (
  "github.com/rakyll/statik/fs"

  _ "./statik" // TODO: Replace with the absolute import path
)

  // ...

  statikFS, err := fs.New()
  if err != nil {
    log.Fatal(err)
  }
  
  // Serve the contents over HTTP.
  http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS)))
  http.ListenAndServe(":8080", nil)

Visit http://localhost:8080/public/path/to/file to see your file.

You can also read the content of a single file:

import (
  "github.com/rakyll/statik/fs"

  _ "./statik" // TODO: Replace with the absolute import path
)

  // ...

  statikFS, err := fs.New()
  if err != nil {
    log.Fatal(err)
  }
  
  // Access individual files by their paths.
  r, err := statikFS.Open("/hello.txt")
  if err != nil {
    log.Fatal(err)
  }    
  defer r.Close()
  contents, err := ioutil.ReadAll(r)
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(string(contents))

There is also a working example under example directory, follow the instructions to build and run it.

Note: The idea and the implementation are hijacked from camlistore. I decided to decouple it from its codebase due to the fact I'm actively in need of a similar solution for many of my projects.

主要指標

概覽
名稱與所有者rakyll/statik
主編程語言Go
編程語言Go (語言數: 1)
平台
許可證Apache License 2.0
所有者活动
創建於2014-02-04 14:54:51
推送於2023-10-18 01:18:28
最后一次提交2020-04-06 12:00:53
發布數8
最新版本名稱v0.1.7 (發布於 )
第一版名稱v0.1.0 (發布於 2016-03-21 16:27:59)
用户参与
星數3.8k
關注者數49
派生數224
提交數99
已啟用問題?
問題數66
打開的問題數24
拉請求數32
打開的拉請求數15
關閉的拉請求數18
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?