goploy/response/File.go

40 lines
757 B
Go
Raw Normal View History

2022-04-09 21:53:37 +08:00
// Copyright 2022 The Goploy Authors. All rights reserved.
// Use of this source code is governed by a GPLv3-style
// license that can be found in the LICENSE file.
2022-01-26 14:33:57 +08:00
package response
import (
"io"
"net/http"
2022-01-26 14:34:11 +08:00
"os"
2022-01-26 14:33:57 +08:00
"strconv"
)
2022-01-26 14:34:11 +08:00
type File struct {
2022-01-26 14:33:57 +08:00
Filename string
}
//JSON response
2022-01-26 14:34:11 +08:00
func (f File) Write(w http.ResponseWriter) error {
file, err := os.Open(f.Filename)
2022-01-26 14:33:57 +08:00
if err != nil {
return err
}
2022-01-26 14:34:11 +08:00
fileStat, err := file.Stat()
2022-01-26 14:33:57 +08:00
if err != nil {
return err
}
w.Header().Set("Content-Disposition", "attachment; filename="+fileStat.Name())
2022-01-26 14:34:11 +08:00
w.Header().Set("Content-Type", "application/x-asciicast")
2022-01-26 14:33:57 +08:00
w.Header().Set("Content-Length", strconv.FormatInt(fileStat.Size(), 10))
2022-01-26 14:34:11 +08:00
_, err = io.Copy(w, file)
2022-01-26 14:33:57 +08:00
if err != nil {
return err
}
return nil
}