/
gingopher.go
70 lines (59 loc) · 1.26 KB
/
gingopher.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
package gingopherjs
import (
"io/ioutil"
"net/http"
"os"
"path"
"strconv"
"strings"
"github.com/gin-gonic/gin"
gbuild "github.com/gopherjs/gopherjs/build"
)
type (
GinGopher struct {
pkg string
}
)
func New(pkg string) (*GinGopher, error) {
return &GinGopher{
pkg: pkg,
}, nil
}
func (g *GinGopher) Handler(c *gin.Context) {
f, err := ioutil.TempFile("", "gingopher")
if err != nil {
c.String(200, "console.error(%s);", strconv.Quote(err.Error()))
return
}
f.Close()
filename := f.Name()
defer os.Remove(filename)
options := &gbuild.Options{
GOROOT: "",
GOPATH: os.Getenv("GOPATH"),
Verbose: false,
Quiet: false,
Watch: false,
CreateMapFile: false,
Minify: false,
Color: true,
}
finalPath := "/"
// Try to deduce the package path.
paths := strings.Split(options.GOPATH, ":")
for _, p := range paths {
candidatePath := path.Join(p, "src", g.pkg)
st, e := os.Stat(candidatePath)
if e == nil && st.IsDir() {
finalPath = candidatePath
break
}
}
s := gbuild.NewSession(options)
err = s.BuildDir(finalPath, g.pkg, filename)
if err != nil {
c.String(200, "console.error(%s);", strconv.Quote(err.Error()))
return
}
http.ServeFile(c.Writer, c.Request, f.Name())
}