// 通过Go 提供的一个net/http 包快速实现一个Go Web服务
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
// 定义注册函数
// w: 相应内容
// r: 请求内容
func sayHelloName(w http.ResponseWriter, r *http.Request) {
// 这里我们写业务逻辑就可以
r.ParseForm() // 解析参数,默认不是解析的
fmt.Println(r.Form) // 请求参数<k,v 数据对
fmt.Println("path = ", r.URL.Path)
// query URL 中KV 数据对
for k, v := range r.Form {
fmt.Println("key : ", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello World") // 这个写入W输出到客户端
}
func main() {
// 通过net/http 包注册函数()把/hello与函数关联起来sayHelloName
http.HandleFunc("/hello", sayHelloName) // 设置访问的路有/hello
//设置监听端口
err := http.ListenAndServe(":8080", nil) // 设置监听端口
if err != nil {
log.Fatal("ListenAndServe : ", err)
}
// 程序启动后,浏览器输入地址
// 1. http://localhost:8080/hello
// 2. http://localhost:8080/hello?name=aiwen&age=30&KK=1121025745
}
http://localhost:8080/hello?name=aiwen&age=30&KK=1121025745
Go Web 服务”指的是使用 Go 编程语言创建的网络服务。具体来说,它是一个基于 Go 语言的程序,通过使用 net/http 包来处理 HTTP 请求和响应,从而实现了一个简单的 Web 服务。