-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
80 lines (74 loc) · 1.67 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"bytes"
"encoding/base64"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"net/http"
"os/exec"
"strings"
)
type request struct {
Code string `json:"code"`
}
func runFormatter(inputCode string) ([]byte, error) {
cmd := exec.Command("rustfmt")
cmd.Stdin = strings.NewReader(inputCode)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return nil, err
}
fmt.Println(out.String())
return out.Bytes(), nil
}
func base64Decoder(input string) ([]byte, error) {
return base64.StdEncoding.DecodeString(input)
}
func base64Encoder(input []byte) string {
return base64.StdEncoding.EncodeToString(input)
}
func main() {
app := fiber.New()
app.Use(cors.New())
app.Get("/formatter/", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"status": "true",
"details": "sorobix-formatter",
"author": "Hemanth Krishna <@DarthBenro008>",
"repository": "https://github." +
"com/sorobix/sorobix-formatter",
})
})
app.Post("/formatter/", func(c *fiber.Ctx) error {
var data request
err := c.BodyParser(&data)
if err != nil {
c.Status(http.StatusBadRequest)
return c.JSON(fiber.Map{
"error": "bad request",
})
}
input, err := base64Decoder(data.Code)
if err != nil {
c.Status(http.StatusBadRequest)
return c.JSON(fiber.Map{
"error": "bad base64 input",
})
}
result, err := runFormatter(string(input))
if err != nil {
c.Status(http.StatusNotAcceptable)
return c.JSON(fiber.Map{
"error": "bad rust code",
"logs": err.Error(),
})
}
return c.JSON(fiber.Map{
"formatted_code": base64Encoder(result),
})
})
app.Listen(":3000")
}