-
Notifications
You must be signed in to change notification settings - Fork 16
/
fmt.go
57 lines (51 loc) · 1.17 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
52
53
54
55
56
57
// 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"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"net/http"
"golang.org/x/tools/imports"
)
type fmtResponse struct {
Body string
Error string
}
func fmtHandler(w http.ResponseWriter, r *http.Request) {
resp := new(fmtResponse)
var body string
var err error
if r.FormValue("imports") == "true" {
var b []byte
b, err = imports.Process("prog.go", []byte(r.FormValue("body")), nil)
body = string(b)
} else {
body, err = gofmt(r.FormValue("body"))
}
if err != nil {
resp.Error = err.Error()
} else {
resp.Body = body
}
json.NewEncoder(w).Encode(resp)
}
func gofmt(body string) (string, error) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "prog.go", body, parser.ParseComments)
if err != nil {
return "", err
}
ast.SortImports(fset, f)
var buf bytes.Buffer
config := &printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
err = config.Fprint(&buf, fset, f)
if err != nil {
return "", err
}
return buf.String(), nil
}