Skip to content

Playgrounds

介紹

對於一些簡單的單文件演示代碼,go 提供了 playground 來在線運行 go 代碼,不需要安裝 go 環境,只需要一個瀏覽器即可。

Playground 開源地址:go-playground (github.com)

官方 Playground 地址:Go Playground - The Go Programming Language

第三方 Playground 地址:The Go Play Space

由於它是一個開源項目,你也可以選擇在自己的服務器上搭建個人 playground,安裝方法見官方文檔。Playground 服務器會將上傳的代碼段存儲到谷歌雲存儲,所以不建議分享敏感代碼。對於國內用戶,建議使用第二個因為不需要魔法上網,但它依舊是基於官方的 Playground 服務器,代碼也會同步到官方那邊的服務器裡面。

筆者自己整了一個玩具goplay,用於在命令行內與 playground 服務器交互,也可以當作 playground HTTP 客戶端庫來使用。

HTTP API

上面提到的都是瀏覽器的方式交互,如果想要從客戶端的角度與 playground 服務器交互,比如編寫一個 vuepress go playground 的插件。由於 playground 服務器本身是一個 HTTP 服務器,我們可以使用 HTTP 的方式來與其進行交互。官方本身沒有提供 API 文檔,下面的 HTTP API 是我從 playground 代碼裡面了解到的,隨著時間的推移可能會有些出入,為了獲取最准確的信息可以自行去倉庫裡面查閱。

官方 playground 服務器地址:play.golang.org,下面演示都以官方服務器為准,如果使用第三方服務器的話替換域名即可。

share

分享代碼段到 playground 服務器上,返回對應的 snippet id。

http
POST https://play.golang.org/share
名稱位置類型必選說明
bodybodystringnone

響應示例

13AbsRp7_S9

compile

編譯並運行指定代碼段,然後返回結果

http
POST https://play.golang.org/compile
名稱位置類型說明
bodyform-datastring代碼段
withVetform-datastring(ture/false)go vet

響應示例

json
{
  "Errors": "",
  "Events": [
    {
      "Message": "Hello, world\n",
      "Kind": "stdout",
      "Delay": 0
    }
  ],
  "Status": 0,
  "IsTest": false,
  "TestsFailed": 0
}

fmt

返回格式化後的代碼段

http
POST https://play.golang.org/fmt
名稱位置類型說明
bodyform-datastring代碼段
importsform-datastring(ture/false)fix imports

響應示例

json
{
  "Body": "// You can edit this code!\n// Click here and start typing.\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello, world\")\n}\n",
  "Error": ""
}

health

對 playground 服務器進行健康檢查

http
GET https://play.golang.org/_ah/health

響應示例

ok

version

查看 playground 服務器 go 版本

http
GET https://play.golang.org/version

響應示例

json
{
  "Version": "go1.21.4",
  "Release": "go1.21",
  "Name": "Go 1.21"
}

view

查看指定 snippet id 的代碼段

http
GET https://play.golang.org/p/{id}.go

響應示例

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

func main() {
  fmt.Println("Hello, world")
}

download

post 方法攜帶 download form 參數會以 attachment 方式返回結果

http
POST https://play.golang.org/p/{id}.go
名稱位置類型說明
downloadform-datastring(true/false)是否下載

響應示例

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

func main() {
  fmt.Println("Hello, world")
}

TIP

如果在使用官方服務器的過程中,提示你無法訪問或者出現下面這種信息

Viewing and/or sharing code snippets is not available in your country for legal reasons.

這是因為某種不可抗力中國大陸地區的用戶無法訪問服務器,並且在 playground 源代碼中也有這麼一個函數

go
func allowShare(r *http.Request) bool {
  if r.Header.Get("X-AppEngine-Country") == "CN" {
    return false
  }
  return true
}

具體原因看這裡 Issue #20065 · golang/go (github.com)

Golang學習網由www.golangdev.cn整理維護