2013-07-24 01:25:00 -06:00
|
|
|
// Copyright 2013 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 playground registers HTTP handlers at "/compile" and "/share" that
|
|
|
|
// proxy requests to the golang.org playground service.
|
|
|
|
// This package may be used unaltered on App Engine.
|
2014-12-08 21:00:58 -07:00
|
|
|
package playground // import "golang.org/x/tools/playground"
|
2013-07-24 01:25:00 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2015-09-01 16:40:41 -06:00
|
|
|
"errors"
|
2013-07-24 01:25:00 -06:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2016-05-02 10:01:04 -06:00
|
|
|
const baseURL = "https://golang.org"
|
2013-07-24 01:25:00 -06:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
http.HandleFunc("/compile", bounce)
|
|
|
|
http.HandleFunc("/share", bounce)
|
|
|
|
}
|
|
|
|
|
|
|
|
func bounce(w http.ResponseWriter, r *http.Request) {
|
|
|
|
b := new(bytes.Buffer)
|
|
|
|
if err := passThru(b, r); err != nil {
|
|
|
|
http.Error(w, "Server error.", http.StatusInternalServerError)
|
|
|
|
report(r, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
io.Copy(w, b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func passThru(w io.Writer, req *http.Request) error {
|
2015-09-01 16:40:41 -06:00
|
|
|
if req.URL.Path == "/share" && !allowShare(req) {
|
|
|
|
return errors.New("Forbidden")
|
|
|
|
}
|
2013-07-24 01:25:00 -06:00
|
|
|
defer req.Body.Close()
|
|
|
|
url := baseURL + req.URL.Path
|
|
|
|
r, err := client(req).Post(url, req.Header.Get("Content-type"), req.Body)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("making POST request: %v", err)
|
|
|
|
}
|
|
|
|
defer r.Body.Close()
|
|
|
|
if _, err := io.Copy(w, r.Body); err != nil {
|
|
|
|
return fmt.Errorf("copying response Body: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2015-09-01 16:40:41 -06:00
|
|
|
|
2015-09-16 20:11:32 -06:00
|
|
|
var onAppengine = false // will be overriden by appengine.go and appenginevm.go
|
2015-09-01 16:40:41 -06:00
|
|
|
|
|
|
|
func allowShare(r *http.Request) bool {
|
|
|
|
if !onAppengine {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
switch r.Header.Get("X-AppEngine-Country") {
|
2015-09-28 01:00:17 -06:00
|
|
|
case "", "ZZ", "CN":
|
2015-09-01 16:40:41 -06:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|