|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io/ioutil" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "strconv" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/labstack/echo" |
| 13 | +) |
| 14 | + |
| 15 | +const defaultPort = 8080 |
| 16 | + |
| 17 | +func getMapResponse(response string) map[string]string { |
| 18 | + return map[string]string{ |
| 19 | + "response": response, |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +type Ping struct { |
| 24 | + Address string `json:"address"` |
| 25 | +} |
| 26 | + |
| 27 | +func pingHandler(c echo.Context) error { |
| 28 | + p := new(Ping) |
| 29 | + if err := c.Bind(p); err != nil { |
| 30 | + c.Error(err) |
| 31 | + return err |
| 32 | + } |
| 33 | + if p.Address == "" { |
| 34 | + return c.JSON( |
| 35 | + http.StatusOK, |
| 36 | + getMapResponse("PONG FROM TARGET"), |
| 37 | + ) |
| 38 | + } |
| 39 | + resp, err := http.Get(fmt.Sprintf("http://%s", p.Address)) |
| 40 | + if err != nil { |
| 41 | + return c.JSON( |
| 42 | + http.StatusBadRequest, |
| 43 | + getMapResponse(fmt.Sprintf("Could not reach address: %s", p.Address)), |
| 44 | + ) |
| 45 | + } |
| 46 | + defer resp.Body.Close() |
| 47 | + body, err := ioutil.ReadAll(resp.Body) |
| 48 | + if err != nil { |
| 49 | + return c.JSON( |
| 50 | + http.StatusBadRequest, |
| 51 | + getMapResponse(fmt.Sprintf("Could not body from response: %s", err)), |
| 52 | + ) |
| 53 | + } |
| 54 | + return c.String(http.StatusOK, string(body)) |
| 55 | +} |
| 56 | + |
| 57 | +type GetFile struct { |
| 58 | + Filename string `json:"filename"` |
| 59 | +} |
| 60 | + |
| 61 | +func fileHandler(c echo.Context) error { |
| 62 | + g := new(GetFile) |
| 63 | + if err := c.Bind(g); err != nil { |
| 64 | + c.Error(err) |
| 65 | + return err |
| 66 | + } |
| 67 | + b, err := ioutil.ReadFile(filepath.Join("/volumes", g.Filename)) |
| 68 | + if err != nil { |
| 69 | + c.Error(err) |
| 70 | + return err |
| 71 | + } |
| 72 | + return c.JSON( |
| 73 | + http.StatusOK, |
| 74 | + getMapResponse(string(b)), |
| 75 | + ) |
| 76 | +} |
| 77 | + |
| 78 | +func main() { |
| 79 | + port := defaultPort |
| 80 | + httpPort := os.Getenv("HTTP_PORT") |
| 81 | + if httpPort != "" { |
| 82 | + port, _ = strconv.Atoi(httpPort) |
| 83 | + } |
| 84 | + e := echo.New() |
| 85 | + e.HideBanner = true |
| 86 | + s := &http.Server{ |
| 87 | + Addr: fmt.Sprintf(":%d", port), |
| 88 | + ReadTimeout: 60 * time.Second, |
| 89 | + WriteTimeout: 60 * time.Second, |
| 90 | + } |
| 91 | + e.GET("/ping", pingHandler) |
| 92 | + e.GET("/volumefile", fileHandler) |
| 93 | + e.Logger.Fatal(e.StartServer(s)) |
| 94 | +} |
0 commit comments