You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.5 KiB

  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package playground registers HTTP handlers at "/compile" and "/share" that
  5. // proxy requests to the golang.org playground service.
  6. // This package may be used unaltered on App Engine.
  7. package playground // import "golang.org/x/tools/playground"
  8. import (
  9. "bytes"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. )
  15. const baseURL = "https://golang.org"
  16. func init() {
  17. http.HandleFunc("/compile", bounce)
  18. http.HandleFunc("/share", bounce)
  19. }
  20. func bounce(w http.ResponseWriter, r *http.Request) {
  21. b := new(bytes.Buffer)
  22. if err := passThru(b, r); err != nil {
  23. http.Error(w, "Server error.", http.StatusInternalServerError)
  24. report(r, err)
  25. return
  26. }
  27. io.Copy(w, b)
  28. }
  29. func passThru(w io.Writer, req *http.Request) error {
  30. if req.URL.Path == "/share" && !allowShare(req) {
  31. return errors.New("Forbidden")
  32. }
  33. defer req.Body.Close()
  34. url := baseURL + req.URL.Path
  35. r, err := client(req).Post(url, req.Header.Get("Content-type"), req.Body)
  36. if err != nil {
  37. return fmt.Errorf("making POST request: %v", err)
  38. }
  39. defer r.Body.Close()
  40. if _, err := io.Copy(w, r.Body); err != nil {
  41. return fmt.Errorf("copying response Body: %v", err)
  42. }
  43. return nil
  44. }
  45. var onAppengine = false // will be overriden by appengine.go and appenginevm.go
  46. func allowShare(r *http.Request) bool {
  47. if !onAppengine {
  48. return true
  49. }
  50. switch r.Header.Get("X-AppEngine-Country") {
  51. case "", "ZZ", "CN":
  52. return false
  53. }
  54. return true
  55. }