golang文件上传服务器

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

适合在工作中临时需要对外传输文件却被防火墙限制的情况

单文件,直接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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值