-
Notifications
You must be signed in to change notification settings - Fork 0
/
fmt.go
51 lines (45 loc) · 1.02 KB
/
fmt.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
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os/exec"
)
func init() {
http.HandleFunc("/fmt", fmtHandler)
}
func fmtHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
body, _ := ioutil.ReadAll(r.Body)
out, err := zigFmt(body)
json.NewEncoder(w).Encode(Output{Error: err, Body: out})
}
}
func zigFmt(code []byte) (stdout string, stderr string) {
cmd := exec.Command("zig", "fmt", "--stdin")
var outb, errb bytes.Buffer
stdin, err := cmd.StdinPipe()
defer stdin.Close()
cmd.Stdout = &outb
cmd.Stderr = &errb
err = cmd.Start()
if err != nil {
log.Println(err.Error())
}
_c, _ := url.QueryUnescape(string(code))
io.WriteString(stdin, _c[5:])
stdin.Close()
cmd.Wait()
stderr = errb.String()
if errb.String() != "" {
stderr = errb.String()[8:]
}
return outb.String(), stderr
}