Go語言是一種高性能、并發(fā)的編程語言,廣泛應用于Web服務和微服務架構。下面是一個簡單的Go語言服務示例:
- 安裝Go環(huán)境:首先需要安裝Go語言開發(fā)環(huán)境,可以通過以下命令進行安裝:
go get -u golang.org/x/net/context
go get -u github.com/gorilla/mux
go get -u github.com/gorilla/handlers
- 編寫一個簡單的Go語言服務:創(chuàng)建一個名為
main.go
的文件,內(nèi)容如下:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", helloHandler)
fmt.Println("Server started at: http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Error starting server: %v
", err)
}
}
- 運行Go語言服務:在命令行中,進入到
main.go
所在的目錄,然后運行以下命令啟動服務:
go run main.go
- 訪問服務:打開瀏覽器,訪問
http://localhost:8080/
,你將看到輸出的“Hello, [URL]!”。
以上就是一個簡單的Go語言服務示例。你可以根據(jù)需要添加更多的功能,例如認證、限流等。
本文內(nèi)容根據(jù)網(wǎng)絡資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉載請注明,如有侵權,聯(lián)系刪除。