├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── build-linux ├── go.mod ├── go.sum ├── handlers.go ├── handlers_test.go ├── main.go └── static ├── index.html ├── logo.ico ├── playground.js ├── robots.txt └── style.css /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: CI 3 | jobs: 4 | test: 5 | strategy: 6 | matrix: 7 | go-version: [1.24.x] 8 | os: [ubuntu-latest, macos-latest, windows-latest] 9 | runs-on: ${{ matrix.os }} 10 | steps: 11 | - name: Install Go 12 | uses: actions/setup-go@v5 13 | with: 14 | go-version: ${{ matrix.go-version }} 15 | - name: Checkout code 16 | uses: actions/checkout@v4 17 | - name: Test 18 | run: | 19 | go vet ./... 20 | go test ./... 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | push-container 2 | zig-play 3 | fly.toml 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:latest 2 | ARG version=0.14.1 3 | RUN apt-get update && apt-get upgrade -y 4 | RUN apt-get install -y wget xz-utils 5 | RUN mkdir -p server/static 6 | WORKDIR /server 7 | RUN wget -q https://ziglang.org/download/${version}/zig-x86_64-linux-${version}.tar.xz && \ 8 | tar xf zig-x86_64-linux-${version}.tar.xz && \ 9 | mv zig-x86_64-linux-${version}/zig /usr/local/bin && \ 10 | mkdir -p /usr/local/bin/lib && \ 11 | mv zig-x86_64-linux-${version}/lib/* /usr/local/bin/lib && \ 12 | rm -rf zig-x86_64-linux-${version}* 13 | COPY zig-play . 14 | COPY static/ static/ 15 | RUN sed -i "s/###version###/${version}/" static/index.html 16 | RUN groupadd -r run && \ 17 | useradd -r -g run -s /usr/sbin/nologin runner && \ 18 | mkdir playground && \ 19 | chown -R runner:run playground 20 | ENV PLAYGROUND_DIR=playground 21 | USER runner 22 | ENTRYPOINT ./zig-play 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Garrett Squire 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zig Playground 2 | 3 | This is a rudimentary online compiler for the [Zig](https://ziglang.org) programming language. It 4 | is inspired by the [Go](https://play.golang.org) playground. 5 | 6 | It's currently served from this [page](https://zig-play.dev). 7 | 8 | ### Setup 9 | The main server is a Go binary that serves up a single HTML page that allows you to enter your Zig 10 | code and then run it. To run it yourself, you will need a Go tool chain which can be installed via 11 | `brew` on a Mac. If you wish to run it locally, you must compile it for your `GOOS` and `GOARCH` 12 | but I have included a small shell script to make a Linux binary that Docker can use as well. You 13 | should also have Zig installed and accessible from within your `$PATH` on the host. 14 | 15 | ### Hosting 16 | In theory this could be run anywhere that a Docker container can execute. Google's Cloud Run may be 17 | a cheap option considering their generous free tier. 18 | 19 | ### FAQ 20 | > What can this playground do? 21 | 22 | It is currently set up to simply run and format a single Zig source file. (i.e. `zig run source.zig` & `zig fmt source.zig`) 23 | 24 | > Are there any timeouts? 25 | 26 | If your code doesn't build within 10 seconds, the server will quit your request. 27 | 28 | > Why am I getting rate-limited? 29 | 30 | You're allowed five compilations per minute which I think is fairly generous. 31 | 32 | > Is it secure? 33 | 34 | Go read the source. I do not collect logs of any kind and am not interested in your data. Unless it 35 | is causing issues to the service. 36 | 37 | > Will this always be available? 38 | 39 | To the best of my ability, I will try and keep this online. 40 | 41 | ### Contact 42 | Feel free to write to hello@zig-play.dev with any questions or comments. 43 | 44 | ### License 45 | MIT 46 | -------------------------------------------------------------------------------- /build-linux: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -eu 4 | 5 | CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build 6 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/gsquire/zig-play 2 | 3 | go 1.24.1 4 | 5 | require ( 6 | github.com/gorilla/handlers v1.5.2 7 | github.com/julienschmidt/httprouter v1.3.0 8 | github.com/justinas/alice v1.2.0 9 | github.com/rs/zerolog v1.33.0 10 | github.com/sethvargo/go-limiter v1.0.0 11 | github.com/unrolled/secure v1.17.0 12 | ) 13 | 14 | require ( 15 | github.com/felixge/httpsnoop v1.0.4 // indirect 16 | github.com/mattn/go-colorable v0.1.14 // indirect 17 | github.com/mattn/go-isatty v0.0.20 // indirect 18 | golang.org/x/sys v0.31.0 // indirect 19 | ) 20 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= 2 | github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= 3 | github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= 4 | github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 5 | github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE= 6 | github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= 7 | github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= 8 | github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= 9 | github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo= 10 | github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA= 11 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= 12 | github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= 13 | github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= 14 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 15 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 16 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 17 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 18 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 19 | github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= 20 | github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= 21 | github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= 22 | github.com/sethvargo/go-limiter v1.0.0 h1:JqW13eWEMn0VFv86OKn8wiYJY/m250WoXdrjRV0kLe4= 23 | github.com/sethvargo/go-limiter v1.0.0/go.mod h1:01b6tW25Ap+MeLYBuD4aHunMrJoNO5PVUFdS9rac3II= 24 | github.com/unrolled/secure v1.17.0 h1:Io7ifFgo99Bnh0J7+Q+qcMzWM6kaDPCA5FroFZEdbWU= 25 | github.com/unrolled/secure v1.17.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= 26 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 27 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 28 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 29 | golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= 30 | golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 31 | -------------------------------------------------------------------------------- /handlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | "os" 9 | "os/exec" 10 | "path/filepath" 11 | "time" 12 | 13 | "github.com/rs/zerolog" 14 | ) 15 | 16 | type Command int 17 | type CtxKey string 18 | 19 | const ( 20 | R Command = iota 21 | F 22 | ) 23 | 24 | const CtxLogger CtxKey = "logger" 25 | 26 | func LoggingMiddleware(h http.Handler, logger zerolog.Logger) http.Handler { 27 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 28 | ctx := context.WithValue(r.Context(), CtxLogger, logger) 29 | h.ServeHTTP(w, r.WithContext(ctx)) 30 | }) 31 | } 32 | 33 | func execute(w http.ResponseWriter, r *http.Request, command Command) { 34 | const defaultZig = "/usr/local/bin/zig" 35 | 36 | var zigExe string 37 | foundZigExe, zigExeErr := exec.LookPath("zig") 38 | if zigExeErr != nil { 39 | zigExe = defaultZig 40 | } else { 41 | zigExe = foundZigExe 42 | } 43 | 44 | logger := r.Context().Value(CtxLogger).(zerolog.Logger) 45 | 46 | // Limit how big a source file can be. 5MB here. 47 | r.Body = http.MaxBytesReader(w, r.Body, 5*1024*1024) 48 | zigSource, err := ioutil.ReadAll(r.Body) 49 | if err != nil { 50 | logger.Error().Err(err).Msg("reading the request body") 51 | http.Error(w, "reading body", http.StatusInternalServerError) 52 | return 53 | } 54 | defer r.Body.Close() 55 | 56 | // Set up the temporary resources. 57 | playgroundDir := os.Getenv("PLAYGROUND_DIR") 58 | dir, err := os.MkdirTemp(playgroundDir, "playground") 59 | if err != nil { 60 | logger.Error().Err(err).Msg("making the temporary directory") 61 | http.Error(w, "creating temporary directory", http.StatusInternalServerError) 62 | return 63 | } 64 | defer os.RemoveAll(dir) 65 | 66 | tmpSource := filepath.Join(dir, "play.zig") 67 | if err := ioutil.WriteFile(tmpSource, []byte(zigSource), 0666); err != nil { 68 | logger.Error().Err(err).Msg("copying the source") 69 | http.Error(w, "copying zig source", http.StatusInternalServerError) 70 | return 71 | } 72 | 73 | // Currently we cap compilation times at thirty seconds. 74 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 75 | defer cancel() 76 | 77 | // We only have two commands for now. 78 | var output []byte 79 | if command == R { 80 | output, err = exec.CommandContext(ctx, zigExe, "run", "--global-cache-dir", dir, tmpSource).CombinedOutput() 81 | } else { 82 | // The global cache directory option is not available for this command. 83 | cmd := fmt.Sprintf("cat %s | ZIG_GLOBAL_CACHE_DIR=%s %s fmt --stdin", tmpSource, dir, zigExe) 84 | output, err = exec.CommandContext(ctx, "bash", "-c", cmd).CombinedOutput() 85 | } 86 | 87 | if err != nil { 88 | logger.Error().Err(err).Msg("running the command") 89 | w.WriteHeader(http.StatusBadRequest) 90 | } 91 | 92 | _, err = w.Write(output) 93 | if err != nil { 94 | logger.Error().Err(err).Msg("writing the response") 95 | http.Error(w, "writing response", http.StatusInternalServerError) 96 | } 97 | } 98 | 99 | func Run(w http.ResponseWriter, r *http.Request) { 100 | logger := r.Context().Value(CtxLogger).(zerolog.Logger) 101 | logger.Info().Msg("running compile") 102 | 103 | execute(w, r, R) 104 | } 105 | 106 | func Fmt(w http.ResponseWriter, r *http.Request) { 107 | logger := r.Context().Value(CtxLogger).(zerolog.Logger) 108 | logger.Info().Msg("running format") 109 | 110 | execute(w, r, F) 111 | } 112 | -------------------------------------------------------------------------------- /handlers_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "net/http" 6 | "net/http/httptest" 7 | "testing" 8 | 9 | "github.com/rs/zerolog" 10 | ) 11 | 12 | func TestBodySizeLimit(t *testing.T) { 13 | payload := bytes.Repeat([]byte("big"), 6*1024*1024) 14 | 15 | req, err := http.NewRequest(http.MethodPost, "/server/run", bytes.NewBuffer(payload)) 16 | if err != nil { 17 | t.Fatal(err) 18 | } 19 | 20 | rr := httptest.NewRecorder() 21 | handler := LoggingMiddleware(http.HandlerFunc(Run), zerolog.Nop()) 22 | 23 | handler.ServeHTTP(rr, req) 24 | 25 | if status := rr.Code; status != http.StatusInternalServerError { 26 | t.Errorf("handler returned wrong status code: got %v want %v", 27 | status, http.StatusInternalServerError) 28 | } 29 | 30 | expected := "reading body\n" 31 | if rr.Body.String() != expected { 32 | t.Errorf("handler returned unexpected body: got %v want %v", 33 | rr.Body.String(), expected) 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "os" 7 | "time" 8 | 9 | "github.com/gorilla/handlers" 10 | "github.com/julienschmidt/httprouter" 11 | "github.com/justinas/alice" 12 | "github.com/rs/zerolog" 13 | "github.com/sethvargo/go-limiter/httplimit" 14 | "github.com/sethvargo/go-limiter/memorystore" 15 | "github.com/unrolled/secure" 16 | ) 17 | 18 | func securitySettings() *secure.Secure { 19 | return secure.New(secure.Options{ 20 | BrowserXssFilter: true, 21 | ContentTypeNosniff: true, 22 | FrameDeny: true, 23 | STSPreload: true, 24 | STSSeconds: 31536000, 25 | }) 26 | } 27 | 28 | func main() { 29 | // Users can compile code 5 times per minute. 30 | rateLimiter, err := memorystore.New(&memorystore.Config{ 31 | Tokens: 5, 32 | Interval: time.Minute, 33 | }) 34 | if err != nil { 35 | log.Fatal("error making rate limiter", err) 36 | } 37 | rlMiddle, err := httplimit.NewMiddleware(rateLimiter, httplimit.IPKeyFunc()) 38 | if err != nil { 39 | log.Fatal(err) 40 | } 41 | 42 | logger := zerolog.New(os.Stdout).With().Timestamp().Logger() 43 | 44 | router := httprouter.New() 45 | router.ServeFiles("/*filepath", http.Dir("static")) 46 | 47 | // We don't rate-limit the static files. So we have to wrap the router with the rate limiting handler. 48 | router.Handler(http.MethodPost, "/server/run", rlMiddle.Handle(http.HandlerFunc(Run))) 49 | router.Handler(http.MethodPost, "/server/fmt", rlMiddle.Handle(http.HandlerFunc(Fmt))) 50 | 51 | chain := alice.New(securitySettings().Handler, handlers.CompressHandler, handlers.RecoveryHandler()).Then(LoggingMiddleware(router, logger)) 52 | log.Fatal(http.ListenAndServe(":8080", chain)) 53 | } 54 | -------------------------------------------------------------------------------- /static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 |