parent
34ff32586a
commit
9e96e95fef
@ -0,0 +1,19 @@
|
||||
#!/bin/bash -
|
||||
#
|
||||
|
||||
set -e
|
||||
|
||||
TARGET=build_tmp/src/github.com/codeskyblue/gosuv
|
||||
HOST="pi3-0"
|
||||
ssh pi@$HOST mkdir -p $TARGET
|
||||
|
||||
rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress \
|
||||
--exclude gosuv --exclude dist --exclude .git \
|
||||
--delete \
|
||||
. pi@$HOST:$TARGET
|
||||
|
||||
echo "Build remotely ..."
|
||||
ssh pi@$HOST bash $TARGET/build_standalone.sh
|
||||
echo "Build finished, copying ..."
|
||||
scp pi@$HOST:$TARGET/gosuv ./dist/gosuv-linux-arm
|
||||
echo "All finished"
|
@ -0,0 +1,12 @@
|
||||
#!/bin/bash -
|
||||
#
|
||||
|
||||
set -e
|
||||
set -o pipefail
|
||||
|
||||
cd $(dirname $0)
|
||||
source "$HOME/.bash_profile"
|
||||
export GOPATH=$GOPATH:/home/pi/build_tmp
|
||||
|
||||
go generate
|
||||
exec go build -tags vfs "$@"
|
@ -1,8 +0,0 @@
|
||||
language: go
|
||||
sudo: false
|
||||
|
||||
go:
|
||||
- 1.3
|
||||
- 1.4
|
||||
- 1.5
|
||||
- tip
|
@ -1,7 +0,0 @@
|
||||
context
|
||||
=======
|
||||
[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context)
|
||||
|
||||
gorilla/context is a general purpose registry for global request variables.
|
||||
|
||||
Read the full documentation here: http://www.gorillatoolkit.org/pkg/context
|
@ -1,143 +0,0 @@
|
||||
// Copyright 2012 The Gorilla Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package context
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
mutex sync.RWMutex
|
||||
data = make(map[*http.Request]map[interface{}]interface{})
|
||||
datat = make(map[*http.Request]int64)
|
||||
)
|
||||
|
||||
// Set stores a value for a given key in a given request.
|
||||
func Set(r *http.Request, key, val interface{}) {
|
||||
mutex.Lock()
|
||||
if data[r] == nil {
|
||||
data[r] = make(map[interface{}]interface{})
|
||||
datat[r] = time.Now().Unix()
|
||||
}
|
||||
data[r][key] = val
|
||||
mutex.Unlock()
|
||||
}
|
||||
|
||||
// Get returns a value stored for a given key in a given request.
|
||||
func Get(r *http.Request, key interface{}) interface{} {
|
||||
mutex.RLock()
|
||||
if ctx := data[r]; ctx != nil {
|
||||
value := ctx[key]
|
||||
mutex.RUnlock()
|
||||
return value
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetOk returns stored value and presence state like multi-value return of map access.
|
||||
func GetOk(r *http.Request, key interface{}) (interface{}, bool) {
|
||||
mutex.RLock()
|
||||
if _, ok := data[r]; ok {
|
||||
value, ok := data[r][key]
|
||||
mutex.RUnlock()
|
||||
return value, ok
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests.
|
||||
func GetAll(r *http.Request) map[interface{}]interface{} {
|
||||
mutex.RLock()
|
||||
if context, ok := data[r]; ok {
|
||||
result := make(map[interface{}]interface{}, len(context))
|
||||
for k, v := range context {
|
||||
result[k] = v
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return result
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if
|
||||
// the request was registered.
|
||||
func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) {
|
||||
mutex.RLock()
|
||||
context, ok := data[r]
|
||||
result := make(map[interface{}]interface{}, len(context))
|
||||
for k, v := range context {
|
||||
result[k] = v
|
||||
}
|
||||
mutex.RUnlock()
|
||||
return result, ok
|
||||
}
|
||||
|
||||
// Delete removes a value stored for a given key in a given request.
|
||||
func Delete(r *http.Request, key interface{}) {
|
||||
mutex.Lock()
|
||||
if data[r] != nil {
|
||||
delete(data[r], key)
|
||||
}
|
||||
mutex.Unlock()
|
||||
}
|
||||
|
||||
// Clear removes all values stored for a given request.
|
||||
//
|
||||
// This is usually called by a handler wrapper to clean up request
|
||||
// variables at the end of a request lifetime. See ClearHandler().
|
||||
func Clear(r *http.Request) {
|
||||
mutex.Lock()
|
||||
clear(r)
|
||||
mutex.Unlock()
|
||||
}
|
||||
|
||||
// clear is Clear without the lock.
|
||||
func clear(r *http.Request) {
|
||||
delete(data, r)
|
||||
delete(datat, r)
|
||||
}
|
||||
|
||||
// Purge removes request data stored for longer than maxAge, in seconds.
|
||||
// It returns the amount of requests removed.
|
||||
//
|
||||
// If maxAge <= 0, all request data is removed.
|
||||
//
|
||||
// This is only used for sanity check: in case context cleaning was not
|
||||
// properly set some request data can be kept forever, consuming an increasing
|
||||
// amount of memory. In case this is detected, Purge() must be called
|
||||
// periodically until the problem is fixed.
|
||||
func Purge(maxAge int) int {
|
||||
mutex.Lock()
|
||||
count := 0
|
||||
if maxAge <= 0 {
|
||||
count = len(data)
|
||||
data = make(map[*http.Request]map[interface{}]interface{})
|
||||
datat = make(map[*http.Request]int64)
|
||||
} else {
|
||||
min := time.Now().Unix() - int64(maxAge)
|
||||
for r := range data {
|
||||
if datat[r] < min {
|
||||
clear(r)
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
mutex.Unlock()
|
||||
return count
|
||||
}
|
||||
|
||||
// ClearHandler wraps an http.Handler and clears request values at the end
|
||||
// of a request lifetime.
|
||||
func ClearHandler(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer Clear(r)
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
@ -1,82 +0,0 @@
|
||||
// Copyright 2012 The Gorilla Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
Package context stores values shared during a request lifetime.
|
||||
|
||||
For example, a router can set variables extracted from the URL and later
|
||||
application handlers can access those values, or it can be used to store
|
||||
sessions values to be saved at the end of a request. There are several
|
||||
others common uses.
|
||||
|
||||
The idea was posted by Brad Fitzpatrick to the go-nuts mailing list:
|
||||
|
||||
http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53
|
||||
|
||||
Here's the basic usage: first define the keys that you will need. The key
|
||||
type is interface{} so a key can be of any type that supports equality.
|
||||
Here we define a key using a custom int type to avoid name collisions:
|
||||
|
||||
package foo
|
||||
|
||||
import (
|
||||
"github.com/gorilla/context"
|
||||
)
|
||||
|
||||
type key int
|
||||
|
||||
const MyKey key = 0
|
||||
|
||||
Then set a variable. Variables are bound to an http.Request object, so you
|
||||
need a request instance to set a value:
|
||||
|
||||
context.Set(r, MyKey, "bar")
|
||||
|
||||
The application can later access the variable using the same key you provided:
|
||||
|
||||
func MyHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// val is "bar".
|
||||
val := context.Get(r, foo.MyKey)
|
||||
|
||||
// returns ("bar", true)
|
||||
val, ok := context.GetOk(r, foo.MyKey)
|
||||
// ...
|
||||
}
|
||||
|
||||
And that's all about the basic usage. We discuss some other ideas below.
|
||||
|
||||
Any type can be stored in the context. To enforce a given type, make the key
|
||||
private and wrap Get() and Set() to accept and return values of a specific
|
||||
type:
|
||||
|
||||
type key int
|
||||
|
||||
const mykey key = 0
|
||||
|
||||
// GetMyKey returns a value for this package from the request values.
|
||||
func GetMyKey(r *http.Request) SomeType {
|
||||
if rv := context.Get(r, mykey); rv != nil {
|
||||
return rv.(SomeType)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMyKey sets a value for this package in the request values.
|
||||
func SetMyKey(r *http.Request, val SomeType) {
|
||||
context.Set(r, mykey, val)
|
||||
}
|
||||
|
||||
Variables must be cleared at the end of a request, to remove all values
|
||||
that were stored. This can be done in an http.Handler, after a request was
|
||||
served. Just call Clear() passing the request:
|
||||
|
||||
context.Clear(r)
|
||||
|
||||
...or use ClearHandler(), which conveniently wraps an http.Handler to clear
|
||||
variables at the end of a request lifetime.
|
||||
|
||||
The Routers from the packages gorilla/mux and gorilla/pat call Clear()
|
||||
so if you are using either of them you don't need to clear the context manually.
|
||||
*/
|
||||
package context
|
@ -1,8 +1,22 @@
|
||||
language: go
|
||||
sudo: false
|
||||
|
||||
go:
|
||||
- 1.3
|
||||
- 1.4
|
||||
- 1.5
|
||||
- tip
|
||||
matrix:
|
||||
include:
|
||||
- go: 1.2
|
||||
- go: 1.3
|
||||
- go: 1.4
|
||||
- go: 1.5
|
||||
- go: 1.6
|
||||
- go: 1.7
|
||||
- go: 1.8
|
||||
- go: tip
|
||||
|
||||
install:
|
||||
- # Skip
|
||||
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d .)
|
||||
- go tool vet .
|
||||
- go test -v -race ./...
|
||||
|
@ -0,0 +1,26 @@
|
||||
// +build !go1.7
|
||||
|
||||
package mux
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/context"
|
||||
)
|
||||
|
||||
func contextGet(r *http.Request, key interface{}) interface{} {
|
||||
return context.Get(r, key)
|
||||
}
|
||||
|
||||
func contextSet(r *http.Request, key, val interface{}) *http.Request {
|
||||
if val == nil {
|
||||
return r
|
||||
}
|
||||
|
||||
context.Set(r, key, val)
|
||||
return r
|
||||
}
|
||||
|
||||
func contextClear(r *http.Request) {
|
||||
context.Clear(r)
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
// +build go1.7
|
||||
|
||||
package mux
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func contextGet(r *http.Request, key interface{}) interface{} {
|
||||
return r.Context().Value(key)
|
||||
}
|
||||
|
||||
func contextSet(r *http.Request, key, val interface{}) *http.Request {
|
||||
if val == nil {
|
||||
return r
|
||||
}
|
||||
|
||||
return r.WithContext(context.WithValue(r.Context(), key, val))
|
||||
}
|
||||
|
||||
func contextClear(r *http.Request) {
|
||||
return
|
||||
}
|
@ -1,6 +1,19 @@
|
||||
language: go
|
||||
sudo: false
|
||||
|
||||
go:
|
||||
- 1.1
|
||||
- 1.2
|
||||
- tip
|
||||
matrix:
|
||||
include:
|
||||
- go: 1.4
|
||||
- go: 1.5
|
||||
- go: 1.6
|
||||
- go: 1.7
|
||||
- go: 1.8
|
||||
- go: tip
|
||||
allow_failures:
|
||||
- go: tip
|
||||
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d .)
|
||||
- go vet $(go list ./... | grep -v /vendor/)
|
||||
- go test -v -race ./...
|
||||
|
@ -0,0 +1,16 @@
|
||||
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.8
|
||||
|
||||
package websocket
|
||||
|
||||
import "crypto/tls"
|
||||
|
||||
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||
if cfg == nil {
|
||||
return &tls.Config{}
|
||||
}
|
||||
return cfg.Clone()
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !go1.8
|
||||
|
||||
package websocket
|
||||
|
||||
import "crypto/tls"
|
||||
|
||||
// cloneTLSConfig clones all public fields except the fields
|
||||
// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
|
||||
// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
|
||||
// config in active use.
|
||||
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||
if cfg == nil {
|
||||
return &tls.Config{}
|
||||
}
|
||||
return &tls.Config{
|
||||
Rand: cfg.Rand,
|
||||
Time: cfg.Time,
|
||||
Certificates: cfg.Certificates,
|
||||
NameToCertificate: cfg.NameToCertificate,
|
||||
GetCertificate: cfg.GetCertificate,
|
||||
RootCAs: cfg.RootCAs,
|
||||
NextProtos: cfg.NextProtos,
|
||||
ServerName: cfg.ServerName,
|
||||
ClientAuth: cfg.ClientAuth,
|
||||
ClientCAs: cfg.ClientCAs,
|
||||
InsecureSkipVerify: cfg.InsecureSkipVerify,
|
||||
CipherSuites: cfg.CipherSuites,
|
||||
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
|
||||
ClientSessionCache: cfg.ClientSessionCache,
|
||||
MinVersion: cfg.MinVersion,
|
||||
MaxVersion: cfg.MaxVersion,
|
||||
CurvePreferences: cfg.CurvePreferences,
|
||||
}
|
||||
}
|
@ -0,0 +1,148 @@
|
||||
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"compress/flate"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6
|
||||
maxCompressionLevel = flate.BestCompression
|
||||
defaultCompressionLevel = 1
|
||||
)
|
||||
|
||||
var (
|
||||
flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
|
||||
flateReaderPool = sync.Pool{New: func() interface{} {
|
||||
return flate.NewReader(nil)
|
||||
}}
|
||||
)
|
||||
|
||||
func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
|
||||
const tail =
|
||||
// Add four bytes as specified in RFC
|
||||
"\x00\x00\xff\xff" +
|
||||
// Add final block to squelch unexpected EOF error from flate reader.
|
||||
"\x01\x00\x00\xff\xff"
|
||||
|
||||
fr, _ := flateReaderPool.Get().(io.ReadCloser)
|
||||
fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil)
|
||||
return &flateReadWrapper{fr}
|
||||
}
|
||||
|
||||
func isValidCompressionLevel(level int) bool {
|
||||
return minCompressionLevel <= level && level <= maxCompressionLevel
|
||||
}
|
||||
|
||||
func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
|
||||
p := &flateWriterPools[level-minCompressionLevel]
|
||||
tw := &truncWriter{w: w}
|
||||
fw, _ := p.Get().(*flate.Writer)
|
||||
if fw == nil {
|
||||
fw, _ = flate.NewWriter(tw, level)
|
||||
} else {
|
||||
fw.Reset(tw)
|
||||
}
|
||||
return &flateWriteWrapper{fw: fw, tw: tw, p: p}
|
||||
}
|
||||
|
||||
// truncWriter is an io.Writer that writes all but the last four bytes of the
|
||||
// stream to another io.Writer.
|
||||
type truncWriter struct {
|
||||
w io.WriteCloser
|
||||
n int
|
||||
p [4]byte
|
||||
}
|
||||
|
||||
func (w *truncWriter) Write(p []byte) (int, error) {
|
||||
n := 0
|
||||
|
||||
// fill buffer first for simplicity.
|
||||
if w.n < len(w.p) {
|
||||
n = copy(w.p[w.n:], p)
|
||||
p = p[n:]
|
||||
w.n += n
|
||||
if len(p) == 0 {
|
||||
return n, nil
|
||||
}
|
||||
}
|
||||
|
||||
m := len(p)
|
||||
if m > len(w.p) {
|
||||
m = len(w.p)
|
||||
}
|
||||
|
||||
if nn, err := w.w.Write(w.p[:m]); err != nil {
|
||||
return n + nn, err
|
||||
}
|
||||
|
||||
copy(w.p[:], w.p[m:])
|
||||
copy(w.p[len(w.p)-m:], p[len(p)-m:])
|
||||
nn, err := w.w.Write(p[:len(p)-m])
|
||||
return n + nn, err
|
||||
}
|
||||
|
||||
type flateWriteWrapper struct {
|
||||
fw *flate.Writer
|
||||
tw *truncWriter
|
||||
p *sync.Pool
|
||||
}
|
||||
|
||||
func (w *flateWriteWrapper) Write(p []byte) (int, error) {
|
||||
if w.fw == nil {
|
||||
return 0, errWriteClosed
|
||||
}
|
||||
return w.fw.Write(p)
|
||||
}
|
||||
|
||||
func (w *flateWriteWrapper) Close() error {
|
||||
if w.fw == nil {
|
||||
return errWriteClosed
|
||||
}
|
||||
err1 := w.fw.Flush()
|
||||
w.p.Put(w.fw)
|
||||
w.fw = nil
|
||||
if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
|
||||
return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
|
||||
}
|
||||
err2 := w.tw.w.Close()
|
||||
if err1 != nil {
|
||||
return err1
|
||||
}
|
||||
return err2
|
||||
}
|
||||
|
||||
type flateReadWrapper struct {
|
||||
fr io.ReadCloser
|
||||
}
|
||||
|
||||
func (r *flateReadWrapper) Read(p []byte) (int, error) {
|
||||
if r.fr == nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
n, err := r.fr.Read(p)
|
||||
if err == io.EOF {
|
||||
// Preemptively place the reader back in the pool. This helps with
|
||||
// scenarios where the application does not call NextReader() soon after
|
||||
// this final read.
|
||||
r.Close()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r *flateReadWrapper) Close() error {
|
||||
if r.fr == nil {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
err := r.fr.Close()
|
||||
flateReaderPool.Put(r.fr)
|
||||
r.fr = nil
|
||||
return err
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,18 @@
|
||||
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.5
|
||||
|
||||
package websocket
|
||||
|
||||
import "io"
|
||||
|
||||
func (c *Conn) read(n int) ([]byte, error) {
|
||||
p, err := c.br.Peek(n)
|
||||
if err == io.EOF {
|
||||
err = errUnexpectedEOF
|
||||
}
|
||||
c.br.Discard(len(p))
|
||||
return p, err
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !go1.5
|
||||
|
||||
package websocket
|
||||
|
||||
import "io"
|
||||
|
||||
func (c *Conn) read(n int) ([]byte, error) {
|
||||
p, err := c.br.Peek(n)
|
||||
if err == io.EOF {
|
||||
err = errUnexpectedEOF
|
||||
}
|
||||
if len(p) > 0 {
|
||||
// advance over the bytes just read
|
||||
io.ReadFull(c.br, p)
|
||||
}
|
||||
return p, err
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
|
||||
// this source code is governed by a BSD-style license that can be found in the
|
||||
// LICENSE file.
|
||||
|
||||
// +build !appengine
|
||||
|
||||
package websocket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
const wordSize = int(unsafe.Sizeof(uintptr(0)))
|
||||
|
||||
func maskBytes(key [4]byte, pos int, b []byte) int {
|
||||
|
||||
// Mask one byte at a time for small buffers.
|
||||
if len(b) < 2*wordSize {
|
||||
for i := range b {
|
||||
b[i] ^= key[pos&3]
|
||||
pos++
|
||||
}
|
||||
return pos & 3
|
||||
}
|
||||
|
||||
// Mask one byte at a time to word boundary.
|
||||
if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
|
||||
n = wordSize - n
|
||||
for i := range b[:n] {
|
||||
b[i] ^= key[pos&3]
|
||||
pos++
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
|
||||
// Create aligned word size key.
|
||||
var k [wordSize]byte
|
||||
for i := range k {
|
||||
k[i] = key[(pos+i)&3]
|
||||
}
|
||||
kw := *(*uintptr)(unsafe.Pointer(&k))
|
||||
|
||||
// Mask one word at a time.
|
||||
n := (len(b) / wordSize) * wordSize
|
||||
for i := 0; i < n; i += wordSize {
|
||||
*(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw
|
||||
}
|
||||
|
||||
// Mask one byte at a time for remaining bytes.
|
||||
b = b[n:]
|
||||
for i := range b {
|
||||
b[i] ^= key[pos&3]
|
||||
pos++
|
||||
}
|
||||
|
||||
return pos & 3
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
|
||||
// this source code is governed by a BSD-style license that can be found in the
|
||||
// LICENSE file.
|
||||
|
||||
// +build appengine
|
||||
|
||||
package websocket
|
||||
|
||||
func maskBytes(key [4]byte, pos int, b []byte) int {
|
||||
for i := range b {
|
||||
b[i] ^= key[pos&3]
|
||||
pos++
|
||||
}
|
||||
return pos & 3
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PreparedMessage caches on the wire representations of a message payload.
|
||||
// Use PreparedMessage to efficiently send a message payload to multiple
|
||||
// connections. PreparedMessage is especially useful when compression is used
|
||||
// because the CPU and memory expensive compression operation can be executed
|
||||
// once for a given set of compression options.
|
||||
type PreparedMessage struct {
|
||||
messageType int
|
||||
data []byte
|
||||
err error
|
||||
mu sync.Mutex
|
||||
frames map[prepareKey]*preparedFrame
|
||||
}
|
||||
|
||||
// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage.
|
||||
type prepareKey struct {
|
||||
isServer bool
|
||||
compress bool
|
||||
compressionLevel int
|
||||
}
|
||||
|
||||
// preparedFrame contains data in wire representation.
|
||||
type preparedFrame struct {
|
||||
once sync.Once
|
||||
data []byte
|
||||
}
|
||||
|
||||
// NewPreparedMessage returns an initialized PreparedMessage. You can then send
|
||||
// it to connection using WritePreparedMessage method. Valid wire
|
||||
// representation will be calculated lazily only once for a set of current
|
||||
// connection options.
|
||||
func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) {
|
||||
pm := &PreparedMessage{
|
||||
messageType: messageType,
|
||||
frames: make(map[prepareKey]*preparedFrame),
|
||||
data: data,
|
||||
}
|
||||
|
||||
// Prepare a plain server frame.
|
||||
_, frameData, err := pm.frame(prepareKey{isServer: true, compress: false})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// To protect against caller modifying the data argument, remember the data
|
||||
// copied to the plain server frame.
|
||||
pm.data = frameData[len(frameData)-len(data):]
|
||||
return pm, nil
|
||||
}
|
||||
|
||||
func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) {
|
||||
pm.mu.Lock()
|
||||
frame, ok := pm.frames[key]
|
||||
if !ok {
|
||||
frame = &preparedFrame{}
|
||||
pm.frames[key] = frame
|
||||
}
|
||||
pm.mu.Unlock()
|
||||
|
||||
var err error
|
||||
frame.once.Do(func() {
|
||||
// Prepare a frame using a 'fake' connection.
|
||||
// TODO: Refactor code in conn.go to allow more direct construction of
|
||||
// the frame.
|
||||
mu := make(chan bool, 1)
|
||||
mu <- true
|
||||
var nc prepareConn
|
||||
c := &Conn{
|
||||
conn: &nc,
|
||||
mu: mu,
|
||||
isServer: key.isServer,
|
||||
compressionLevel: key.compressionLevel,
|
||||
enableWriteCompression: true,
|
||||
writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize),
|
||||
}
|
||||
if key.compress {
|
||||
c.newCompressionWriter = compressNoContextTakeover
|
||||
}
|
||||
err = c.WriteMessage(pm.messageType, pm.data)
|
||||
frame.data = nc.buf.Bytes()
|
||||
})
|
||||
return pm.messageType, frame.data, err
|
||||
}
|
||||
|
||||
type prepareConn struct {
|
||||
buf bytes.Buffer
|
||||
net.Conn
|
||||
}
|
||||
|
||||
func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) }
|
||||
func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil }
|
@ -0,0 +1,21 @@
|
||||
package vfsutil
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
// File implements http.FileSystem using the native file system restricted to a
|
||||
// specific file served at root.
|
||||
//
|
||||
// While the FileSystem.Open method takes '/'-separated paths, a File's string
|
||||
// value is a filename on the native file system, not a URL, so it is separated
|
||||
// by filepath.Separator, which isn't necessarily '/'.
|
||||
type File string
|
||||
|
||||
func (f File) Open(name string) (http.File, error) {
|
||||
if name != "/" {
|
||||
return nil, &os.PathError{Op: "open", Path: name, Err: os.ErrNotExist}
|
||||
}
|
||||
return os.Open(string(f))
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
// Package vfsutil implements some I/O utility functions for http.FileSystem.
|
||||
package vfsutil
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
// ReadDir reads the contents of the directory associated with file and
|
||||
// returns a slice of FileInfo values in directory order.
|
||||
func ReadDir(fs http.FileSystem, name string) ([]os.FileInfo, error) {
|
||||
f, err := fs.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return f.Readdir(0)
|
||||
}
|
||||
|
||||
// Stat returns the FileInfo structure describing file.
|
||||
func Stat(fs http.FileSystem, name string) (os.FileInfo, error) {
|
||||
f, err := fs.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return f.Stat()
|
||||
}
|
||||
|
||||
// ReadFile reads the file named by path from fs and returns the contents.
|
||||
func ReadFile(fs http.FileSystem, path string) ([]byte, error) {
|
||||
rc, err := fs.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rc.Close()
|
||||
return ioutil.ReadAll(rc)
|
||||
}
|
@ -0,0 +1,148 @@
|
||||
package vfsutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
pathpkg "path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
|
||||
"golang.org/x/tools/godoc/vfs"
|
||||
)
|
||||
|
||||
// Walk walks the filesystem rooted at root, calling walkFn for each file or
|
||||
// directory in the filesystem, including root. All errors that arise visiting files
|
||||
// and directories are filtered by walkFn. The files are walked in lexical
|
||||
// order.
|
||||
func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error {
|
||||
info, err := Stat(fs, root)
|
||||
if err != nil {
|
||||
return walkFn(root, nil, err)
|
||||
}
|
||||
return walk(fs, root, info, walkFn)
|
||||
}
|
||||
|
||||
// readDirNames reads the directory named by dirname and returns
|
||||
// a sorted list of directory entries.
|
||||
func readDirNames(fs http.FileSystem, dirname string) ([]string, error) {
|
||||
fis, err := ReadDir(fs, dirname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := make([]string, len(fis))
|
||||
for i := range fis {
|
||||
names[i] = fis[i].Name()
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// walk recursively descends path, calling walkFn.
|
||||
func walk(fs http.FileSystem, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
|
||||
err := walkFn(path, info, nil)
|
||||
if err != nil {
|
||||
if info.IsDir() && err == filepath.SkipDir {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
names, err := readDirNames(fs, path)
|
||||
if err != nil {
|
||||
return walkFn(path, info, err)
|
||||
}
|
||||
|
||||
for _, name := range names {
|
||||
filename := pathpkg.Join(path, name)
|
||||
fileInfo, err := Stat(fs, filename)
|
||||
if err != nil {
|
||||
if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
err = walk(fs, filename, fileInfo, walkFn)
|
||||
if err != nil {
|
||||
if !fileInfo.IsDir() || err != filepath.SkipDir {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WalkFilesFunc is the type of the function called for each file or directory visited by WalkFiles.
|
||||
// It's like filepath.WalkFunc, except it provides an additional ReadSeeker parameter for file being visited.
|
||||
type WalkFilesFunc func(path string, info os.FileInfo, rs io.ReadSeeker, err error) error
|
||||
|
||||
// WalkFiles walks the filesystem rooted at root, calling walkFn for each file or
|
||||
// directory in the filesystem, including root. In addition to FileInfo, it passes an
|
||||
// ReadSeeker to walkFn for each file it visits.
|
||||
func WalkFiles(fs http.FileSystem, root string, walkFn WalkFilesFunc) error {
|
||||
file, info, err := openStat(fs, root)
|
||||
if err != nil {
|
||||
return walkFn(root, nil, nil, err)
|
||||
}
|
||||
return walkFiles(fs, root, info, file, walkFn)
|
||||
}
|
||||
|
||||
// walkFiles recursively descends path, calling walkFn.
|
||||
// It closes the input file after it's done with it, so the caller shouldn't.
|
||||
func walkFiles(fs http.FileSystem, path string, info os.FileInfo, file vfs.ReadSeekCloser, walkFn WalkFilesFunc) error {
|
||||
err := walkFn(path, info, file, nil)
|
||||
file.Close()
|
||||
if err != nil {
|
||||
if info.IsDir() && err == filepath.SkipDir {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
names, err := readDirNames(fs, path)
|
||||
if err != nil {
|
||||
return walkFn(path, info, nil, err)
|
||||
}
|
||||
|
||||
for _, name := range names {
|
||||
filename := pathpkg.Join(path, name)
|
||||
file, fileInfo, err := openStat(fs, filename)
|
||||
if err != nil {
|
||||
if err := walkFn(filename, nil, nil, err); err != nil && err != filepath.SkipDir {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
err = walkFiles(fs, filename, fileInfo, file, walkFn)
|
||||
// file is closed by walkFiles, so we don't need to close it here.
|
||||
if err != nil {
|
||||
if !fileInfo.IsDir() || err != filepath.SkipDir {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// openStat performs Open and Stat and returns results, or first error encountered.
|
||||
// The caller is responsible for closing the returned file when done.
|
||||
func openStat(fs http.FileSystem, name string) (http.File, os.FileInfo, error) {
|
||||
f, err := fs.Open(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return f, fi, nil
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- 1.7
|
||||
- tip
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
fast_finish: true
|
||||
install:
|
||||
- # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step).
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d -s .)
|
||||
- go tool vet .
|
||||
- go test -v -race ./...
|
@ -0,0 +1,10 @@
|
||||
Contributing
|
||||
============
|
||||
|
||||
vfsgen is open source, thanks for considering contributing!
|
||||
|
||||
Please note that vfsgen aims to be simple and minimalistic, with as little to configure as possible. If you'd like to remove or simplify code (while having tests continue to pass), fix bugs, or improve code (e.g., add missing error checking, etc.), PRs and issues are welcome.
|
||||
|
||||
However, if you'd like to add new functionality that increases complexity or scope, please make an issue and discuss your proposal first. I'm unlikely to accept such changes outright. It might be that your request is already a part of other similar packages, or it might fit in their scope better. See [Comparison and Alternatives](https://github.com/shurcooL/vfsgen/tree/README-alternatives-and-comparison-section#comparison) sections.
|
||||
|
||||
Thank you!
|
@ -0,0 +1,171 @@
|
||||
vfsgen
|
||||
======
|
||||
|
||||
[![Build Status](https://travis-ci.org/shurcooL/vfsgen.svg?branch=master)](https://travis-ci.org/shurcooL/vfsgen) [![GoDoc](https://godoc.org/github.com/shurcooL/vfsgen?status.svg)](https://godoc.org/github.com/shurcooL/vfsgen)
|
||||
|
||||
Package vfsgen takes an http.FileSystem (likely at `go generate` time) and
|
||||
generates Go code that statically implements the provided http.FileSystem.
|
||||
|
||||
Features:
|
||||
|
||||
- Efficient generated code without unneccessary overhead.
|
||||
|
||||
- Uses gzip compression internally (selectively, only for files that compress well).
|
||||
|
||||
- Enables direct access to internal gzip compressed bytes via an optional interface.
|
||||
|
||||
- Outputs `gofmt`ed Go code.
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
```bash
|
||||
go get -u github.com/shurcooL/vfsgen
|
||||
```
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
This code will generate an assets_vfsdata.go file with `var assets http.FileSystem = ...` that statically implements the contents of "assets" directory.
|
||||
|
||||
```Go
|
||||
var fs http.FileSystem = http.Dir("assets")
|
||||
|
||||
err := vfsgen.Generate(fs, vfsgen.Options{})
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
```
|
||||
|
||||
Then, in your program, you can use `assets` as any other [`http.FileSystem`](https://godoc.org/net/http#FileSystem), for example:
|
||||
|
||||
```Go
|
||||
file, err := assets.Open("/some/file.txt")
|
||||
if err != nil { ... }
|
||||
defer file.Close()
|
||||
```
|
||||
|
||||
```Go
|
||||
http.Handle("/assets/", http.FileServer(assets))
|
||||
```
|
||||
|
||||
### `go generate` Usage
|
||||
|
||||
vfsgen is great to use with go generate directives. The code invoking `vfsgen.Generate` can go in an assets_generate.go file, which can then be invoked via "//go:generate go run assets_generate.go". The input virtual filesystem can read directly from disk, or it can be more involved.
|
||||
|
||||
By using build tags, you can create a development mode where assets are loaded directly from disk via `http.Dir`, but then statically implemented for final releases.
|
||||
|
||||
For example, suppose your source filesystem is defined in a package with import path "example.com/project/data" as:
|
||||
|
||||
```Go
|
||||
// +build dev
|
||||
|
||||
package data
|
||||
|
||||
// Assets contains project assets.
|
||||
var Assets http.FileSystem = http.Dir("assets")
|
||||
```
|
||||
|
||||
When built with the "dev" build tag, accessing `data.Assets` will read from disk directly via `http.Dir`.
|
||||
|
||||
A generate helper file assets_generate.go can be invoked via "//go:generate go run -tags=dev assets_generate.go" directive:
|
||||
|
||||
```Go
|
||||
// +build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"example.com/project/data"
|
||||
"github.com/shurcooL/vfsgen"
|
||||
)
|
||||
|
||||
func main() {
|
||||
err := vfsgen.Generate(data.Assets, vfsgen.Options{
|
||||
PackageName: "data",
|
||||
BuildTags: "!dev",
|
||||
VariableName: "Assets",
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that "dev" build tag is used to access the source filesystem, and the output file will contain "!dev" build tag. That way, the statically implemented version will be used during normal builds and `go get`, when custom builds tags are not specified.
|
||||
|
||||
### `vfsgendev` Usage
|
||||
|
||||
`vfsgendev` is a binary that can be used to replace the need for the assets_generate.go file.
|
||||
|
||||
Make sure it's installed and available in your PATH.
|
||||
|
||||
```bash
|
||||
go get -u github.com/shurcooL/vfsgen/cmd/vfsgendev
|
||||
```
|
||||
|
||||
Then the "//go:generate go run -tags=dev assets_generate.go" directive can be replaced with:
|
||||
|
||||
```
|
||||
//go:generate vfsgendev -source="example.com/project/data".Assets
|
||||
```
|
||||
|
||||
vfsgendev accesses the source variable using "dev" build tag, and generates an output file with "!dev" build tag.
|
||||
|
||||
### Additional Embedded Information
|
||||
|
||||
All compressed files implement [`httpgzip.GzipByter` interface](https://godoc.org/github.com/shurcooL/httpgzip#GzipByter) for efficient direct access to the internal compressed bytes:
|
||||
|
||||
```Go
|
||||
// GzipByter is implemented by compressed files for
|
||||
// efficient direct access to the internal compressed bytes.
|
||||
type GzipByter interface {
|
||||
// GzipBytes returns gzip compressed contents of the file.
|
||||
GzipBytes() []byte
|
||||
}
|
||||
```
|
||||
|
||||
Files that have been determined to not be worth gzip compressing (their compressed size is larger than original) implement [`httpgzip.NotWorthGzipCompressing` interface](https://godoc.org/github.com/shurcooL/httpgzip#NotWorthGzipCompressing):
|
||||
|
||||
```Go
|
||||
// NotWorthGzipCompressing is implemented by files that were determined
|
||||
// not to be worth gzip compressing (the file size did not decrease as a result).
|
||||
type NotWorthGzipCompressing interface {
|
||||
// NotWorthGzipCompressing is a noop. It's implemented in order to indicate
|
||||
// the file is not worth gzip compressing.
|
||||
NotWorthGzipCompressing()
|
||||
}
|
||||
```
|
||||
|
||||
Comparison
|
||||
----------
|
||||
|
||||
vfsgen aims to be conceptually simple to use. The [`http.FileSystem`](https://godoc.org/net/http#FileSystem) abstraction is central to vfsgen. It's used as both input for code generation, and as output in the generated code.
|
||||
|
||||
That enables great flexibility through orthogonality, since helpers and wrappers can operate on `http.FileSystem` without knowing about vfsgen. If you want, you can perform pre-processing, minifying assets, merging folders, filtering out files and otherwise modifying input via generic `http.FileSystem` middleware.
|
||||
|
||||
It avoids unneccessary overhead by merging what was previously done with two distinct packages into a single package.
|
||||
|
||||
It strives to be the best in its class in terms of code quality and efficiency of generated code. However, if your use goals are different, there are other similar packages that may fit your needs better.
|
||||
|
||||
### Alternatives
|
||||
|
||||
- [`go-bindata`](https://github.com/jteeuwen/go-bindata) - Reads from disk, generates Go code that provides access to data via a [custom API](https://github.com/jteeuwen/go-bindata#accessing-an-asset).
|
||||
- [`go-bindata-assetfs`](https://github.com/elazarl/go-bindata-assetfs) - Takes output of go-bindata and provides a wrapper that implements `http.FileSystem` interface (the same as what vfsgen outputs directly).
|
||||
- [`becky`](https://github.com/tv42/becky) - Embeds assets as string literals in Go source.
|
||||
- [`statik`](https://github.com/rakyll/statik) - Embeds a directory of static files to be accessed via `http.FileSystem` interface (sounds very similar to vfsgen); implementation sourced from [camlistore](https://camlistore.org).
|
||||
- [`go.rice`](https://github.com/GeertJohan/go.rice) - Makes working with resources such as HTML, JS, CSS, images and templates very easy.
|
||||
- [`esc`](https://github.com/mjibson/esc) - Embeds files into Go programs and provides `http.FileSystem` interfaces to them.
|
||||
- [`staticfiles`](https://github.com/bouk/staticfiles) - Allows you to embed a directory of files into your Go binary.
|
||||
|
||||
Attribution
|
||||
-----------
|
||||
|
||||
This package was originally based on the excellent work by [@jteeuwen](https://github.com/jteeuwen) on [`go-bindata`](https://github.com/jteeuwen/go-bindata) and [@elazarl](https://github.com/elazarl) on [`go-bindata-assetfs`](https://github.com/elazarl/go-bindata-assetfs).
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
- [MIT License](https://opensource.org/licenses/mit-license.php)
|
@ -0,0 +1,45 @@
|
||||
package vfsgen
|
||||
|
||||
import "io"
|
||||
|
||||
// commentWriter writes a Go comment to the underlying io.Writer,
|
||||
// using line comment form (//).
|
||||
type commentWriter struct {
|
||||
W io.Writer
|
||||
wroteSlashes bool // Wrote "//" at the beginning of the current line.
|
||||
}
|
||||
|
||||
func (c *commentWriter) Write(p []byte) (int, error) {
|
||||
var n int
|
||||
for i, b := range p {
|
||||
if !c.wroteSlashes {
|
||||
s := "//"
|
||||
if b != '\n' {
|
||||
s = "// "
|
||||
}
|
||||
if _, err := io.WriteString(c.W, s); err != nil {
|
||||
return n, err
|
||||
}
|
||||
c.wroteSlashes = true
|
||||
}
|
||||
n0, err := c.W.Write(p[i : i+1])
|
||||
n += n0
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
if b == '\n' {
|
||||
c.wroteSlashes = false
|
||||
}
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (c *commentWriter) Close() error {
|
||||
if !c.wroteSlashes {
|
||||
if _, err := io.WriteString(c.W, "//"); err != nil {
|
||||
return err
|
||||
}
|
||||
c.wroteSlashes = true
|
||||
}
|
||||
return nil
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
/*
|
||||
Package vfsgen takes an http.FileSystem (likely at `go generate` time) and
|
||||
generates Go code that statically implements the provided http.FileSystem.
|
||||
|
||||
Features:
|
||||
|
||||
- Efficient generated code without unneccessary overhead.
|
||||
|
||||
- Uses gzip compression internally (selectively, only for files that compress well).
|
||||
|
||||
- Enables direct access to internal gzip compressed bytes via an optional interface.
|
||||
|
||||
- Outputs `gofmt`ed Go code.
|
||||
*/
|
||||
package vfsgen
|
@ -0,0 +1,45 @@
|
||||
package vfsgen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Options for vfsgen code generation.
|
||||
type Options struct {
|
||||
// Filename of the generated Go code output (including extension).
|
||||
// If left empty, it defaults to "{{toLower .VariableName}}_vfsdata.go".
|
||||
Filename string
|
||||
|
||||
// PackageName is the name of the package in the generated code.
|
||||
// If left empty, it defaults to "main".
|
||||
PackageName string
|
||||
|
||||
// BuildTags are the optional build tags in the generated code.
|
||||
// The build tags syntax is specified by the go tool.
|
||||
BuildTags string
|
||||
|
||||
// VariableName is the name of the http.FileSystem variable in the generated code.
|
||||
// If left empty, it defaults to "assets".
|
||||
VariableName string
|
||||
|
||||
// VariableComment is the comment of the http.FileSystem variable in the generated code.
|
||||
// If left empty, it defaults to "{{.VariableName}} statically implements the virtual filesystem provided to vfsgen.".
|
||||
VariableComment string
|
||||
}
|
||||
|
||||
// fillMissing sets default values for mandatory options that are left empty.
|
||||
func (opt *Options) fillMissing() {
|
||||
if opt.PackageName == "" {
|
||||
opt.PackageName = "main"
|
||||
}
|
||||
if opt.VariableName == "" {
|
||||
opt.VariableName = "assets"
|
||||
}
|
||||
if opt.Filename == "" {
|
||||
opt.Filename = fmt.Sprintf("%s_vfsdata.go", strings.ToLower(opt.VariableName))
|
||||
}
|
||||
if opt.VariableComment == "" {
|
||||
opt.VariableComment = fmt.Sprintf("%s statically implements the virtual filesystem provided to vfsgen.", opt.VariableName)
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package vfsgen
|
||||
|
||||
import (
|
||||
"io"
|
||||
)
|
||||
|
||||
// stringWriter writes given bytes to underlying io.Writer as a Go interpreted string literal value,
|
||||
// not including double quotes. It tracks the total number of bytes written.
|
||||
type stringWriter struct {
|
||||
io.Writer
|
||||
N int64 // Total bytes written.
|
||||
}
|
||||
|
||||
func (sw *stringWriter) Write(p []byte) (n int, err error) {
|
||||
const hex = "0123456789abcdef"
|
||||
buf := []byte{'\\', 'x', 0, 0}
|
||||
for _, b := range p {
|
||||
buf[2], buf[3] = hex[b/16], hex[b%16]
|
||||
_, err = sw.Writer.Write(buf)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
n++
|
||||
sw.N++
|
||||
}
|
||||
return n, nil
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
# This source code refers to The Go Authors for copyright purposes.
|
||||
# The master list of authors is in the main Go distribution,
|
||||
# visible at http://tip.golang.org/AUTHORS.
|
@ -0,0 +1,3 @@
|
||||
# This source code was written by the Go contributors.
|
||||
# The master list of contributors is in the main Go distribution,
|
||||
# visible at http://tip.golang.org/CONTRIBUTORS.
|
@ -0,0 +1,3 @@
|
||||
# This source code refers to The Go Authors for copyright purposes.
|
||||
# The master list of authors is in the main Go distribution,
|
||||
# visible at http://tip.golang.org/AUTHORS.
|
@ -0,0 +1,3 @@
|
||||
# This source code was written by the Go contributors.
|
||||
# The master list of contributors is in the main Go distribution,
|
||||
# visible at http://tip.golang.org/CONTRIBUTORS.
|
@ -1,16 +1,16 @@
|
||||
Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
|
||||
Copyright (c) 2009 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
@ -0,0 +1,22 @@
|
||||
Additional IP Rights Grant (Patents)
|
||||
|
||||
"This implementation" means the copyrightable works distributed by
|
||||
Google as part of the Go project.
|
||||
|
||||
Google hereby grants to You a perpetual, worldwide, non-exclusive,
|
||||
no-charge, royalty-free, irrevocable (except as stated in this section)
|
||||
patent license to make, have made, use, offer to sell, sell, import,
|
||||
transfer and otherwise run, modify and propagate the contents of this
|
||||
implementation of Go, where such license applies only to those patent
|
||||
claims, both currently owned or controlled by Google and acquired in
|
||||
the future, licensable by Google that are necessarily infringed by this
|
||||
implementation of Go. This grant does not include claims that would be
|
||||
infringed only as a consequence of further modification of this
|
||||
implementation. If you or your agent or exclusive licensee institute or
|
||||
order or agree to the institution of patent litigation against any
|
||||
entity (including a cross-claim or counterclaim in a lawsuit) alleging
|
||||
that this implementation of Go or any code incorporated within this
|
||||
implementation of Go constitutes direct or contributory patent
|
||||
infringement, or inducement of patent infringement, then any patent
|
||||
rights granted to you under this License for this implementation of Go
|
||||
shall terminate as of the date such litigation is filed.
|
@ -0,0 +1,381 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vfs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
pathpkg "path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Setting debugNS = true will enable debugging prints about
|
||||
// name space translations.
|
||||
const debugNS = false
|
||||
|
||||
// A NameSpace is a file system made up of other file systems
|
||||
// mounted at specific locations in the name space.
|
||||
//
|
||||
// The representation is a map from mount point locations
|
||||
// to the list of file systems mounted at that location. A traditional
|
||||
// Unix mount table would use a single file system per mount point,
|
||||
// but we want to be able to mount multiple file systems on a single
|
||||
// mount point and have the system behave as if the union of those
|
||||
// file systems were present at the mount point.
|
||||
// For example, if the OS file system has a Go installation in
|
||||
// c:\Go and additional Go path trees in d:\Work1 and d:\Work2, then
|
||||
// this name space creates the view we want for the godoc server:
|
||||
//
|
||||
// NameSpace{
|
||||
// "/": {
|
||||
// {old: "/", fs: OS(`c:\Go`), new: "/"},
|
||||
// },
|
||||
// "/src/pkg": {
|
||||
// {old: "/src/pkg", fs: OS(`c:\Go`), new: "/src/pkg"},
|
||||
// {old: "/src/pkg", fs: OS(`d:\Work1`), new: "/src"},
|
||||
// {old: "/src/pkg", fs: OS(`d:\Work2`), new: "/src"},
|
||||
// },
|
||||
// }
|
||||
//
|
||||
// This is created by executing:
|
||||
//
|
||||
// ns := NameSpace{}
|
||||
// ns.Bind("/", OS(`c:\Go`), "/", BindReplace)
|
||||
// ns.Bind("/src/pkg", OS(`d:\Work1`), "/src", BindAfter)
|
||||
// ns.Bind("/src/pkg", OS(`d:\Work2`), "/src", BindAfter)
|
||||
//
|
||||
// A particular mount point entry is a triple (old, fs, new), meaning that to
|
||||
// operate on a path beginning with old, replace that prefix (old) with new
|
||||
// and then pass that path to the FileSystem implementation fs.
|
||||
//
|
||||
// Given this name space, a ReadDir of /src/pkg/code will check each prefix
|
||||
// of the path for a mount point (first /src/pkg/code, then /src/pkg, then /src,
|
||||
// then /), stopping when it finds one. For the above example, /src/pkg/code
|
||||
// will find the mount point at /src/pkg:
|
||||
//
|
||||
// {old: "/src/pkg", fs: OS(`c:\Go`), new: "/src/pkg"},
|
||||
// {old: "/src/pkg", fs: OS(`d:\Work1`), new: "/src"},
|
||||
// {old: "/src/pkg", fs: OS(`d:\Work2`), new: "/src"},
|
||||
//
|
||||
// ReadDir will when execute these three calls and merge the results:
|
||||
//
|
||||
// OS(`c:\Go`).ReadDir("/src/pkg/code")
|
||||
// OS(`d:\Work1').ReadDir("/src/code")
|
||||
// OS(`d:\Work2').ReadDir("/src/code")
|
||||
//
|
||||
// Note that the "/src/pkg" in "/src/pkg/code" has been replaced by
|
||||
// just "/src" in the final two calls.
|
||||
//
|
||||
// OS is itself an implementation of a file system: it implements
|
||||
// OS(`c:\Go`).ReadDir("/src/pkg/code") as ioutil.ReadDir(`c:\Go\src\pkg\code`).
|
||||
//
|
||||
// Because the new path is evaluated by fs (here OS(root)), another way
|
||||
// to read the mount table is to mentally combine fs+new, so that this table:
|
||||
//
|
||||
// {old: "/src/pkg", fs: OS(`c:\Go`), new: "/src/pkg"},
|
||||
// {old: "/src/pkg", fs: OS(`d:\Work1`), new: "/src"},
|
||||
// {old: "/src/pkg", fs: OS(`d:\Work2`), new: "/src"},
|
||||
//
|
||||
// reads as:
|
||||
//
|
||||
// "/src/pkg" -> c:\Go\src\pkg
|
||||
// "/src/pkg" -> d:\Work1\src
|
||||
// "/src/pkg" -> d:\Work2\src
|
||||
//
|
||||
// An invariant (a redundancy) of the name space representation is that
|
||||
// ns[mtpt][i].old is always equal to mtpt (in the example, ns["/src/pkg"]'s
|
||||
// mount table entries always have old == "/src/pkg"). The 'old' field is
|
||||
// useful to callers, because they receive just a []mountedFS and not any
|
||||
// other indication of which mount point was found.
|
||||
//
|
||||
type NameSpace map[string][]mountedFS
|
||||
|
||||
// A mountedFS handles requests for path by replacing
|
||||
// a prefix 'old' with 'new' and then calling the fs methods.
|
||||
type mountedFS struct {
|
||||
old string
|
||||
fs FileSystem
|
||||
new string
|
||||
}
|
||||
|
||||
// hasPathPrefix returns true if x == y or x == y + "/" + more
|
||||
func hasPathPrefix(x, y string) bool {
|
||||
return x == y || strings.HasPrefix(x, y) && (strings.HasSuffix(y, "/") || strings.HasPrefix(x[len(y):], "/"))
|
||||
}
|
||||
|
||||
// translate translates path for use in m, replacing old with new.
|
||||
//
|
||||
// mountedFS{"/src/pkg", fs, "/src"}.translate("/src/pkg/code") == "/src/code".
|
||||
func (m mountedFS) translate(path string) string {
|
||||
path = pathpkg.Clean("/" + path)
|
||||
if !hasPathPrefix(path, m.old) {
|
||||
panic("translate " + path + " but old=" + m.old)
|
||||
}
|
||||
return pathpkg.Join(m.new, path[len(m.old):])
|
||||
}
|
||||
|
||||
func (NameSpace) String() string {
|
||||
return "ns"
|
||||
}
|
||||
|
||||
// Fprint writes a text representation of the name space to w.
|
||||
func (ns NameSpace) Fprint(w io.Writer) {
|
||||
fmt.Fprint(w, "name space {\n")
|
||||
var all []string
|
||||
for mtpt := range ns {
|
||||
all = append(all, mtpt)
|
||||
}
|
||||
sort.Strings(all)
|
||||
for _, mtpt := range all {
|
||||
fmt.Fprintf(w, "\t%s:\n", mtpt)
|
||||
for _, m := range ns[mtpt] {
|
||||
fmt.Fprintf(w, "\t\t%s %s\n", m.fs, m.new)
|
||||
}
|
||||
}
|
||||
fmt.Fprint(w, "}\n")
|
||||
}
|
||||
|
||||
// clean returns a cleaned, rooted path for evaluation.
|
||||
// It canonicalizes the path so that we can use string operations
|
||||
// to analyze it.
|
||||
func (NameSpace) clean(path string) string {
|
||||
return pathpkg.Clean("/" + path)
|
||||
}
|
||||
|
||||
type BindMode int
|
||||
|
||||
const (
|
||||
BindReplace BindMode = iota
|
||||
BindBefore
|
||||
BindAfter
|
||||
)
|
||||
|
||||
// Bind causes references to old to redirect to the path new in newfs.
|
||||
// If mode is BindReplace, old redirections are discarded.
|
||||
// If mode is BindBefore, this redirection takes priority over existing ones,
|
||||
// but earlier ones are still consulted for paths that do not exist in newfs.
|
||||
// If mode is BindAfter, this redirection happens only after existing ones
|
||||
// have been tried and failed.
|
||||
func (ns NameSpace) Bind(old string, newfs FileSystem, new string, mode BindMode) {
|
||||
old = ns.clean(old)
|
||||
new = ns.clean(new)
|
||||
m := mountedFS{old, newfs, new}
|
||||
var mtpt []mountedFS
|
||||
switch mode {
|
||||
case BindReplace:
|
||||
mtpt = append(mtpt, m)
|
||||
case BindAfter:
|
||||
mtpt = append(mtpt, ns.resolve(old)...)
|
||||
mtpt = append(mtpt, m)
|
||||
case BindBefore:
|
||||
mtpt = append(mtpt, m)
|
||||
mtpt = append(mtpt, ns.resolve(old)...)
|
||||
}
|
||||
|
||||
// Extend m.old, m.new in inherited mount point entries.
|
||||
for i := range mtpt {
|
||||
m := &mtpt[i]
|
||||
if m.old != old {
|
||||
if !hasPathPrefix(old, m.old) {
|
||||
// This should not happen. If it does, panic so
|
||||
// that we can see the call trace that led to it.
|
||||
panic(fmt.Sprintf("invalid Bind: old=%q m={%q, %s, %q}", old, m.old, m.fs.String(), m.new))
|
||||
}
|
||||
suffix := old[len(m.old):]
|
||||
m.old = pathpkg.Join(m.old, suffix)
|
||||
m.new = pathpkg.Join(m.new, suffix)
|
||||
}
|
||||
}
|
||||
|
||||
ns[old] = mtpt
|
||||
}
|
||||
|
||||
// resolve resolves a path to the list of mountedFS to use for path.
|
||||
func (ns NameSpace) resolve(path string) []mountedFS {
|
||||
path = ns.clean(path)
|
||||
for {
|
||||
if m := ns[path]; m != nil {
|
||||
if debugNS {
|
||||
fmt.Printf("resolve %s: %v\n", path, m)
|
||||
}
|
||||
return m
|
||||
}
|
||||
if path == "/" {
|
||||
break
|
||||
}
|
||||
path = pathpkg.Dir(path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Open implements the FileSystem Open method.
|
||||
func (ns NameSpace) Open(path string) (ReadSeekCloser, error) {
|
||||
var err error
|
||||
for _, m := range ns.resolve(path) {
|
||||
if debugNS {
|
||||
fmt.Printf("tx %s: %v\n", path, m.translate(path))
|
||||
}
|
||||
r, err1 := m.fs.Open(m.translate(path))
|
||||
if err1 == nil {
|
||||
return r, nil
|
||||
}
|
||||
if err == nil {
|
||||
err = err1
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = &os.PathError{Op: "open", Path: path, Err: os.ErrNotExist}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// stat implements the FileSystem Stat and Lstat methods.
|
||||
func (ns NameSpace) stat(path string, f func(FileSystem, string) (os.FileInfo, error)) (os.FileInfo, error) {
|
||||
var err error
|
||||
for _, m := range ns.resolve(path) {
|
||||
fi, err1 := f(m.fs, m.translate(path))
|
||||
if err1 == nil {
|
||||
return fi, nil
|
||||
}
|
||||
if err == nil {
|
||||
err = err1
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = &os.PathError{Op: "stat", Path: path, Err: os.ErrNotExist}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (ns NameSpace) Stat(path string) (os.FileInfo, error) {
|
||||
return ns.stat(path, FileSystem.Stat)
|
||||
}
|
||||
|
||||
func (ns NameSpace) Lstat(path string) (os.FileInfo, error) {
|
||||
return ns.stat(path, FileSystem.Lstat)
|
||||
}
|
||||
|
||||
// dirInfo is a trivial implementation of os.FileInfo for a directory.
|
||||
type dirInfo string
|
||||
|
||||
func (d dirInfo) Name() string { return string(d) }
|
||||
func (d dirInfo) Size() int64 { return 0 }
|
||||
func (d dirInfo) Mode() os.FileMode { return os.ModeDir | 0555 }
|
||||
func (d dirInfo) ModTime() time.Time { return startTime }
|
||||
func (d dirInfo) IsDir() bool { return true }
|
||||
func (d dirInfo) Sys() interface{} { return nil }
|
||||
|
||||
var startTime = time.Now()
|
||||
|
||||
// ReadDir implements the FileSystem ReadDir method. It's where most of the magic is.
|
||||
// (The rest is in resolve.)
|
||||
//
|
||||
// Logically, ReadDir must return the union of all the directories that are named
|
||||
// by path. In order to avoid misinterpreting Go packages, of all the directories
|
||||
// that contain Go source code, we only include the files from the first,
|
||||
// but we include subdirectories from all.
|
||||
//
|
||||
// ReadDir must also return directory entries needed to reach mount points.
|
||||
// If the name space looks like the example in the type NameSpace comment,
|
||||
// but c:\Go does not have a src/pkg subdirectory, we still want to be able
|
||||
// to find that subdirectory, because we've mounted d:\Work1 and d:\Work2
|
||||
// there. So if we don't see "src" in the directory listing for c:\Go, we add an
|
||||
// entry for it before returning.
|
||||
//
|
||||
func (ns NameSpace) ReadDir(path string) ([]os.FileInfo, error) {
|
||||
path = ns.clean(path)
|
||||
|
||||
var (
|
||||
haveGo = false
|
||||
haveName = map[string]bool{}
|
||||
all []os.FileInfo
|
||||
err error
|
||||
first []os.FileInfo
|
||||
)
|
||||
|
||||
for _, m := range ns.resolve(path) {
|
||||
dir, err1 := m.fs.ReadDir(m.translate(path))
|
||||
if err1 != nil {
|
||||
if err == nil {
|
||||
err = err1
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if dir == nil {
|
||||
dir = []os.FileInfo{}
|
||||
}
|
||||
|
||||
if first == nil {
|
||||
first = dir
|
||||
}
|
||||
|
||||
// If we don't yet have Go files in 'all' and this directory
|
||||
// has some, add all the files from this directory.
|
||||
// Otherwise, only add subdirectories.
|
||||
useFiles := false
|
||||
if !haveGo {
|
||||
for _, d := range dir {
|
||||
if strings.HasSuffix(d.Name(), ".go") {
|
||||
useFiles = true
|
||||
haveGo = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, d := range dir {
|
||||
name := d.Name()
|
||||
if (d.IsDir() || useFiles) && !haveName[name] {
|
||||
haveName[name] = true
|
||||
all = append(all, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We didn't find any directories containing Go files.
|
||||
// If some directory returned successfully, use that.
|
||||
if !haveGo {
|
||||
for _, d := range first {
|
||||
if !haveName[d.Name()] {
|
||||
haveName[d.Name()] = true
|
||||
all = append(all, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Built union. Add any missing directories needed to reach mount points.
|
||||
for old := range ns {
|
||||
if hasPathPrefix(old, path) && old != path {
|
||||
// Find next element after path in old.
|
||||
elem := old[len(path):]
|
||||
elem = strings.TrimPrefix(elem, "/")
|
||||
if i := strings.Index(elem, "/"); i >= 0 {
|
||||
elem = elem[:i]
|
||||
}
|
||||
if !haveName[elem] {
|
||||
haveName[elem] = true
|
||||
all = append(all, dirInfo(elem))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(all) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sort.Sort(byName(all))
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// byName implements sort.Interface.
|
||||
type byName []os.FileInfo
|
||||
|
||||
func (f byName) Len() int { return len(f) }
|
||||
func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
|
||||
func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
|
@ -0,0 +1,65 @@
|
||||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vfs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
pathpkg "path"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// OS returns an implementation of FileSystem reading from the
|
||||
// tree rooted at root. Recording a root is convenient everywhere
|
||||
// but necessary on Windows, because the slash-separated path
|
||||
// passed to Open has no way to specify a drive letter. Using a root
|
||||
// lets code refer to OS(`c:\`), OS(`d:\`) and so on.
|
||||
func OS(root string) FileSystem {
|
||||
return osFS(root)
|
||||
}
|
||||
|
||||
type osFS string
|
||||
|
||||
func (root osFS) String() string { return "os(" + string(root) + ")" }
|
||||
|
||||
func (root osFS) resolve(path string) string {
|
||||
// Clean the path so that it cannot possibly begin with ../.
|
||||
// If it did, the result of filepath.Join would be outside the
|
||||
// tree rooted at root. We probably won't ever see a path
|
||||
// with .. in it, but be safe anyway.
|
||||
path = pathpkg.Clean("/" + path)
|
||||
|
||||
return filepath.Join(string(root), path)
|
||||
}
|
||||
|
||||
func (root osFS) Open(path string) (ReadSeekCloser, error) {
|
||||
f, err := os.Open(root.resolve(path))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
if fi.IsDir() {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("Open: %s is a directory", path)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (root osFS) Lstat(path string) (os.FileInfo, error) {
|
||||
return os.Lstat(root.resolve(path))
|
||||
}
|
||||
|
||||
func (root osFS) Stat(path string) (os.FileInfo, error) {
|
||||
return os.Stat(root.resolve(path))
|
||||
}
|
||||
|
||||
func (root osFS) ReadDir(path string) ([]os.FileInfo, error) {
|
||||
return ioutil.ReadDir(root.resolve(path)) // is sorted
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package vfs defines types for abstract file system access and provides an
|
||||
// implementation accessing the file system of the underlying OS.
|
||||
package vfs
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
)
|
||||
|
||||
// The FileSystem interface specifies the methods godoc is using
|
||||
// to access the file system for which it serves documentation.
|
||||
type FileSystem interface {
|
||||
Opener
|
||||
Lstat(path string) (os.FileInfo, error)
|
||||
Stat(path string) (os.FileInfo, error)
|
||||
ReadDir(path string) ([]os.FileInfo, error)
|
||||
String() string
|
||||
}
|
||||
|
||||
// Opener is a minimal virtual filesystem that can only open regular files.
|
||||
type Opener interface {
|
||||
Open(name string) (ReadSeekCloser, error)
|
||||
}
|
||||
|
||||
// A ReadSeekCloser can Read, Seek, and Close.
|
||||
type ReadSeekCloser interface {
|
||||
io.Reader
|
||||
io.Seeker
|
||||
io.Closer
|
||||
}
|
||||
|
||||
// ReadFile reads the file named by path from fs and returns the contents.
|
||||
func ReadFile(fs Opener, path string) ([]byte, error) {
|
||||
rc, err := fs.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rc.Close()
|
||||
return ioutil.ReadAll(rc)
|
||||
}
|
Loading…
Reference in new issue