|
| 1 | +// Copyright 2020 The CUE Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package main |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "io" |
| 20 | + "net/http" |
| 21 | +) |
| 22 | + |
| 23 | +const userAgent = "cuelang.org/play/ playground snippet fetcher" |
| 24 | + |
| 25 | +func handle(w http.ResponseWriter, r *http.Request) { |
| 26 | + cors(w) |
| 27 | + f := func(format string, args ...interface{}) { |
| 28 | + fmt.Fprintf(w, format, args...) |
| 29 | + } |
| 30 | + client := &http.Client{} |
| 31 | + if r.Method == "POST" { |
| 32 | + // Share |
| 33 | + url := fmt.Sprintf("https://play.golang.org/share") |
| 34 | + req, err := http.NewRequest("POST", url, nil) |
| 35 | + if err != nil { |
| 36 | + w.WriteHeader(http.StatusInternalServerError) |
| 37 | + f("Failed to create onwards GET URL: %v", err) |
| 38 | + return |
| 39 | + } |
| 40 | + req.Header.Add("User-Agent", userAgent) |
| 41 | + req.Body = r.Body |
| 42 | + resp, err := client.Do(req) |
| 43 | + if err != nil { |
| 44 | + w.WriteHeader(http.StatusInternalServerError) |
| 45 | + f("Failed in onward request: %v", err) |
| 46 | + return |
| 47 | + } |
| 48 | + io.Copy(w, resp.Body) |
| 49 | + } else { |
| 50 | + // Retrieve via the parameter id |
| 51 | + url := fmt.Sprintf("https://play.golang.org/p/%v.go", r.FormValue("id")) |
| 52 | + req, err := http.NewRequest("GET", url, nil) |
| 53 | + if err != nil { |
| 54 | + w.WriteHeader(http.StatusInternalServerError) |
| 55 | + f("Failed to create onwards GET URL: %v", err) |
| 56 | + return |
| 57 | + } |
| 58 | + req.Header.Add("User-Agent", userAgent) |
| 59 | + resp, err := client.Do(req) |
| 60 | + if err != nil { |
| 61 | + w.WriteHeader(http.StatusInternalServerError) |
| 62 | + f("Failed in onward request: %v", err) |
| 63 | + return |
| 64 | + } |
| 65 | + io.Copy(w, resp.Body) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +func main() { |
| 70 | + http.HandleFunc("/.netlify/functions/snippets", handle) |
| 71 | + serve() |
| 72 | +} |
0 commit comments