go gin server初體驗
阿新 • • 發佈:2018-12-11
gin可用作go環境的web server, 很好用,來玩下:
1. go get github.com/gin-gonic/gin 下載並安裝gin庫
結果出現:go build github.com/ugorji/go/codec: /usr/lib/go-1.6/pkg/tool/linux_amd64/compile: signal: killed
在網上查了一下,是oom所致, 用dmesg確認了一下, 果然如此:
[114220.386131] [ 4027] 500 4027 20792 155 41 4 0 0 curl [114220.386132] Out of memory: Kill process 4018 (compile) score 542 or sacrifice child [114220.387049] Killed process 4018 (compile) total-vm:492476kB, anon-rss:478772kB, file-rss:0kB
買的騰訊雲機器, 記憶體小, 暈。
索性重啟ubuntu, 再go get github.com/gin-gonic/gin一下, 就OK了。
2. 寫服務s.go
package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
go run s.go跑起來
3. 發請求:
[email protected]:~$ curl "http://localhost/ping"
curl: (7) Failed to connect to localhost port 80: Connection refused
[email protected]:~$
[email protected]:~$ curl "http://localhost:8080/ping"
{"message":"pong"}[email protected]:~$
收到請求了。
另外, 注意到:
[email protected]:~/taoge/go$ go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/ubuntu/go"
GORACE=""
GOROOT="/usr/lib/go-1.6"
GOTOOLDIR="/usr/lib/go-1.6/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT="1"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
我們去GOPATH路徑下看下:
[email protected]:~/go/src/github.com/gin-gonic/gin$ pwd
/home/ubuntu/go/src/github.com/gin-gonic/gin
[email protected]:~/go/src/github.com/gin-gonic/gin$ ls
auth.go context_17_test.go doc.go internal README.md routes_test.go
AUTHORS.md context_appengine.go errors.go LICENSE recovery.go testdata
auth_test.go context.go errors_test.go logger.go recovery_test.go test_helpers.go
BENCHMARKS.md context_test.go examples logger_test.go render tree.go
benchmarks_test.go CONTRIBUTING.md fs.go Makefile response_writer_1.7.go tree_test.go
binding coverage.sh gin.go middleware_test.go response_writer_1.8.go utils.go
CHANGELOG.md debug.go gin_integration_test.go mode.go response_writer.go utils_test.go
codecov.yml debug_test.go ginS mode_test.go response_writer_test.go vendor
CODE_OF_CONDUCT.md deprecated.go gin_test.go path.go routergroup.go wercker.yml
context_17.go deprecated_test.go githubapi_test.go path_test.go routergroup_test.go
[email protected]:~/go/src/github.com/gin-gonic/gin$
這就是gin對應的包所在的目錄。
gin server可以吐回單純的文字串, 也自然能吐回html, 讓瀏覽器來顯示, s.go程式碼為:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func first(c *gin.Context) {
s := `
<html">
<body>
<input type="text" name="admin_name"></input></td>
</body>
</html>
`
c.Header("Content-Type", "text/html; charset=utf-8") // 不可少
c.String(http.StatusOK, "%s", s)
}
func main() {
r := gin.Default()
r.GET("/", first)
r.Run(":8080")
}
gin功能很強大,如上僅僅是簡單demo.
不多說。