下面是一个示例的Golang HTTP文件服务器,实现了您提到的功能:
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/download", downloadHandler)
http.HandleFunc("/query", queryHandler)
server := &http.Server{
Addr: ":8080",
Handler: nil,
}
log.Println("Server started on port 8080")
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Error retrieving the file")
return
}
defer file.Close()
f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Error saving the file")
return
}
defer f.Close()
io.Copy(f, file)
fmt.Fprintf(w, "File uploaded successfully")
}
func downloadHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("filename")
if filename == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Missing 'filename' parameter")
return
}
fileStat, err := os.Stat(filename)
if os.IsNotExist(err) || fileStat.IsDir() {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "File not found")
return
}
fileSize := strconv.FormatInt(fileStat.Size(), 10)
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", fileSize)
http.ServeFile(w, r, filename)
}
func queryHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("filename")
if filename == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Missing 'filename' parameter")
return
}
fileStat, err := os.Stat(filename)
if os.IsNotExist(err) || fileStat.IsDir() {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "File not found")
return
}
fileSize := strconv.FormatInt(fileStat.Size(), 10)
fmt.Fprintf(w, "File: %s\nSize: %s bytes\n", filename, fileSize)
}
以上是一个简单的示例,您可以根据自己的需求进行修改和扩展。这个示例包含了文件上传、下载和查询功能,并支持range下载。关于HTTP、HTTPS、HTTP2协议的支持取决于您所使用的服务器配置。要实现gracefulShutdown和gracefulRestart能力,可以结合第三方库如github.com/facebookgo/grace/gracehttp来实现。
内容由零声教学AI助手提供,问题来源于学员提问




