feat: echo(get,set file)

This commit is contained in:
loveuer
2024-04-05 12:47:51 +08:00
parent 4ae56d1726
commit c8ea9ec9f4
3 changed files with 55 additions and 8 deletions

View File

@ -1,4 +1,4 @@
FROM golang:1.20.14-alpine3.19 AS builder
FROM golang:latest AS builder
WORKDIR /app/build
@ -7,6 +7,8 @@ COPY go.sum .
COPY service/echo/main.go .
ENV GOPROXY https://goproxy.io
ENV GOOS linux
ENV GOARCH amd64
RUN go mod download && go build -ldflags='-s -w' -o echo_app .

View File

@ -3,7 +3,9 @@ package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"time"
@ -37,6 +39,51 @@ func main() {
return c.Next()
})
app.Get("/echo/file", func(c *nf.Ctx) error {
type Req struct {
Filename string `query:"filename"`
Download bool `query:"download"`
}
var (
err error
req = new(Req)
file *os.File
bs []byte
)
if err = c.QueryParser(req); err != nil {
return resp.Resp400(c, err.Error())
}
if req.Filename == "" {
return resp.Resp400(c, req, "empty file name")
}
filename := path.Join(root, path.Base(req.Filename))
if file, err = os.Open(filename); err != nil {
return resp.Resp400(c, nf.Map{"filepath": filename, "err": err.Error()})
}
if bs, err = io.ReadAll(file); err != nil {
return resp.Resp400(c, nf.Map{"filepath": filename, "err": err.Error()})
}
ct := ""
if len(bs) > 512 {
ct = http.DetectContentType(bs[:512])
} else {
ct = http.DetectContentType(bs)
}
c.SetHeader("Content-Type", ct)
_, err = c.Write(bs)
return err
})
app.Post("/echo/file", func(c *nf.Ctx) error {
type Req struct {
Filename string