适合在工作中临时需要对外传输文件却被防火墙限制的情况
单文件,直接build
package main
import (
"encoding/json"
"flag"
"net/http"
"os"
"crypto/rand"
"github.com/sirupsen/logrus"
"crypto/sha1"
"errors"
"fmt"
"io"
"io/ioutil"
"path"
"regexp"
"strings"
)
var logger *logrus.Logger
var (
rePathUpload = regexp.MustCompile(`^/upload$`)
rePathFiles = regexp.MustCompile(`^/files/([^/]+)$`)
errTokenMismatch = errors.New("token mismatched")
errMissingToken = errors.New("missing token")
protectedMethods = []string{
http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut}
)
type response struct {
OK bool `json:"ok"`
}
type uploadedResponse struct {
response
Path string `json:"path"`
}
func newUploadedResponse(path string) uploadedResponse {
return uploadedResponse{
response: response{
OK: true}, Path: path}
}
type errorResponse struct {
response
Message string `json:"error"`
}
func newErrorResponse(err error) errorResponse {
return errorResponse{
response: response{
OK: false}, Message: err.Error()}
}
func writeError(w http.ResponseWriter, err error) (int, error) {
body := newErrorResponse(err)
b, e := json.Marshal(body)
// if an error is occured on marshaling, write empty value as response.
if e != nil {
return w.Write([]byte{
})
}
return w.Write(b)
}
func writeSuccess(w http.ResponseWriter, path string) (int, error) {
body := newUploadedResponse(path)
b, e := json.Marshal(body)
// if an error is occured on marshaling, write empty value as response.
if e != nil {
return w.Write([]byte{
})
}
return w.Write(b)
}
func getSize(content io.Seeker) (int64, error) {
size, err := content.Seek(0, os.SEEK_END)
if err != nil {
return 0, err
}
_, err = content.Seek(0, io.SeekStart)
if err != nil {
return 0, err
}
return size, nil
}
// Server represents a simple-upload server.
type Server struct {
DocumentRoot string
// MaxUploadSize limits the size of the uploaded content, specified with "byte".
MaxUploadSize int64
SecureToken string
EnableCORS bool
}
// NewServer creates a new simple-upload server.
func NewServer(documentRoot string, maxUploadSize int64, token string, enableCORS bool) Server {
return Server{
DocumentRoot: documentRoot,
MaxUploadSize: maxUploadSize,
SecureToken: token,
EnableCORS: enableCORS,
}
}
func (s Server) handleGet(w http.ResponseWriter, r *http.Request) {
if !rePathFiles.MatchString(r.URL.Path) {
w.WriteHeader(http.StatusNotFound)
writeError(w, fmt.Errorf("\"%s\" is not found", r.URL.Path))
return
}
if s.EnableCORS {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
http.StripPrefix("/files/", http.FileServer(http.Dir(s.DocumentRoot))).ServeHTTP(w

本文介绍了一个简单的文件上传服务器实现,适用于工作场景中因防火墙限制而难以直接传输文件的情况。该服务器支持通过POST和PUT方法上传文件,并具备基本的安全验证和CORS支持。
最低0.47元/天 解锁文章
480

被折叠的 条评论
为什么被折叠?



