wide/playground/build.go

76 lines
1.8 KiB
Go
Raw Normal View History

2017-03-14 17:40:45 +03:00
// Copyright (c) 2014-2017, b3log.org & hacpai.com
2015-02-13 04:59:51 +03:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package playground
import (
"encoding/json"
"html/template"
"net/http"
"os/exec"
"path/filepath"
"strings"
"github.com/b3log/wide/conf"
"github.com/b3log/wide/session"
"github.com/b3log/wide/util"
)
// BuildHandler handles request of Playground building.
func BuildHandler(w http.ResponseWriter, r *http.Request) {
2015-11-24 12:39:35 +03:00
result := util.NewResult()
defer util.RetResult(w, r, result)
2015-02-13 04:59:51 +03:00
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
2015-11-24 12:39:35 +03:00
result.Succ = false
2015-02-13 04:59:51 +03:00
return
}
2015-02-13 05:50:14 +03:00
fileName := args["fileName"].(string)
filePath := filepath.Clean(conf.Wide.Playground + "/" + fileName)
2015-02-13 04:59:51 +03:00
suffix := ""
if util.OS.IsWindows() {
suffix = ".exe"
}
2015-11-24 12:39:35 +03:00
data := map[string]interface{}{}
2015-11-27 11:55:28 +03:00
result.Data = &data
2015-11-24 12:39:35 +03:00
2015-02-13 04:59:51 +03:00
executable := filepath.Clean(conf.Wide.Playground + "/" + strings.Replace(fileName, ".go", suffix, -1))
cmd := exec.Command("go", "build", "-o", executable, filePath)
out, err := cmd.CombinedOutput()
2015-11-24 12:39:35 +03:00
2015-02-13 04:59:51 +03:00
data["output"] = template.HTML(string(out))
if nil != err {
2015-11-24 12:39:35 +03:00
result.Succ = false
2015-02-13 04:59:51 +03:00
return
}
data["executable"] = executable
}