博客 / 詳情

返回

golang實現一個簡單的HTTP服務(go語言實現http get傳參)

如何使用golang實現http服務在瀏覽器實現傳遞參數?本文通過一段簡單的代碼使用go語言實現http服務器。

代碼

h.go

package main
 
import (
    "fmt"
    "net/http"
)

// 處理GET請求
func handleGet(writer http.ResponseWriter, request *http.Request) {
    
    // 獲取URL的參數
    query := request.URL.Query()
    // 獲得URL的id
    id := query.Get("id")

    // 輸出到頁面(JSON)
    fmt.Fprintf(writer, `{'id':`+id+`}`)
}

func main() {
    http.HandleFunc("/", handleGet)
    fmt.Printf("http://127.0.0.1:8080")
    // 在8080端口開啓HTTP服務
    err := http.ListenAndServe("127.0.0.1:8080", nil)
    if err != nil {
        fmt.Println("http start failed err:", err)
        return
    }
}

cmd運行

image.png

瀏覽器demo

image.png

作者

TANKING

user avatar yilezhiming 頭像 kevin_5d8582b6a85cd 頭像 jzuc 頭像 643104191 頭像 winfacter 頭像 zbooksea 頭像 2dian718 頭像
7 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.