Skip to content

Commit

Permalink
feat: download head request set etag
Browse files Browse the repository at this point in the history
  • Loading branch information
pupilcc committed Jan 9, 2024
1 parent 279fd02 commit 0e8f6fe
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 24 deletions.
17 changes: 17 additions & 0 deletions internal/service/ssl_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package service
import (
"autossl/internal/domain"
"autossl/util"
"crypto/md5"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -121,3 +122,19 @@ func GetCerts() []domain.Cert {

return certs
}

func Etag(filePath string) (string, error) {
etag := ""
file, err := os.Open(filePath)
if err != nil {
return etag, err
}
defer file.Close()

hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return etag, err
}
etag = fmt.Sprintf("%x", hash.Sum(nil))
return etag, nil
}
15 changes: 0 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,6 @@ func main() {
// Logger
e.Use(middleware.RequestLogger())

// Head request support
e.Use(AllowHeadRequestsMiddleware())

// Start the service
e.Logger.Fatal(e.Start(":1323"))
}

func AllowHeadRequestsMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if c.Request().Method == echo.HEAD {
c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8)
return c.NoContent(http.StatusOK)
}
return next(c)
}
}
}
23 changes: 14 additions & 9 deletions web/ssl.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ package web
import (
"autossl/internal/domain"
"autossl/internal/service"
"crypto/md5"
"fmt"
"github.com/labstack/echo/v4"
"io"
"net/http"
"os"
"path/filepath"
Expand All @@ -16,6 +14,7 @@ func SSLRoutes(e *echo.Echo) {
r := e.Group("/ssl")
r.POST("/import", upload)
r.GET("/dl/:uuid", download)
r.HEAD("/dl/:uuid", downloadHead)
r.GET("", list)
}

Expand All @@ -42,22 +41,28 @@ func upload(c echo.Context) error {

func download(c echo.Context) error {
uuid := c.Param("uuid")

filePath := filepath.Join(service.CertPath, uuid)
file, err := os.Open(filePath)

etag, err := service.Etag(filePath)
if err != nil {
return err
}
defer file.Close()
c.Response().Header().Set("ETag", etag)

return c.File(filePath)
}

hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
func downloadHead(c echo.Context) error {
uuid := c.Param("uuid")
filePath := filepath.Join(service.CertPath, uuid)

etag, err := service.Etag(filePath)
if err != nil {
return err
}
etag := fmt.Sprintf("%x", hash.Sum(nil))
c.Response().Header().Set("ETag", etag)

return c.File(filePath)
return c.NoContent(http.StatusOK)
}

func list(c echo.Context) error {
Expand Down

0 comments on commit 0e8f6fe

Please sign in to comment.