How to use golang to implement http service and pass parameters in browser? This article uses a simple code to implement an http server in go language.

code

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 run

image.png

browser demo

image.png

author

TANKING


TANKING
4.8k 声望493 粉丝

热爱分享,热爱创作,热爱研究。