Skip to content

Commit

Permalink
refactor liveness object server & remove echo dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
faceair committed Aug 20, 2023
1 parent 27027b3 commit 46406b3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 119 deletions.
19 changes: 0 additions & 19 deletions livenessObject/go.mod

This file was deleted.

47 changes: 0 additions & 47 deletions livenessObject/go.sum

This file was deleted.

76 changes: 23 additions & 53 deletions livenessObject/speedtest.go
Original file line number Diff line number Diff line change
@@ -1,64 +1,34 @@
package main

import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"io"
"net/http"
"strconv"
)

func main() {
StartServ()
}

func StartServ() {
e := echo.New()
e.HideBanner = true
e.Use(middleware.Recover())
e.Use(middleware.Logger())
e.GET("/", func(c echo.Context) error {
return c.HTML(http.StatusOK, `
<h1>SpeedTest Working....</h1>
`)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/html")
w.Write([]byte(`<h1>SpeedTest Works</h1>`))
})
e.Any("/liveness", func(c echo.Context) error {
return c.NoContent(http.StatusNoContent)
http.HandleFunc("/liveness", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})

e.GET("/_down", GenBigSizeHandler)
e.Logger.Fatal(e.Start(":8080"))
}

func GenBigSizeHandler(c echo.Context) error {
u := c.QueryParams()
b := u.Get("bytes")
bytes, err := strconv.ParseInt(b, 10, 64)
if err != nil {
return err
}

c.Response().Header().Set("Content-Disposition", "attachment; filename=largefile")
c.Response().Header().Set("Content-Type", "application/octet-stream")

zeroReader := &ZeroReader{}

_, err = io.CopyN(c.Response().Writer, zeroReader, bytes)
if err != nil {
return err
}

c.Response().Flush()
return c.NoContent(http.StatusNoContent)
}

// ZeroReader 是一个只生成零值字节的 Reader
type ZeroReader struct{}

func (z *ZeroReader) Read(p []byte) (int, error) {
// 把 p 填充满零值字节
for i := range p {
p[i] = 0
}
return len(p), nil
http.HandleFunc("/_down", func(w http.ResponseWriter, r *http.Request) {
byteSize, err := strconv.Atoi(r.URL.Query().Get("bytes"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Disposition", "attachment; filename=largefile")
w.Header().Add("Content-Type", "application/octet-stream")

zeroBytes := []byte("0")
for i := 0; i < byteSize; i++ {
w.Write(zeroBytes)
}
})
http.ListenAndServe(":8080", nil)
}

0 comments on commit 46406b3

Please sign in to comment.