windows下使用go1.15.5模拟HttpServer
- go环境安装
从https://go.dev/dl/
下载安装文件go1.15.5.windows-amd64.msi
,正常安装后可 能查版本go version
编写一个HelloWorld.go
演示功能
package main
import (
"fmt"
"time"
)
func main(){
fmt.Println("Hello World!!!")
time.Sleep(time.Duration(5)*time.Second) //休眠5秒,不然打包成exe后一打开就关闭了
}
编译后执行或直接执行,包名为main,并引入了 fmt 以及 time包
go build HelloWorld.go
go run HelloWorld.go
build
后会生成HelloWorld.exe
执行文件
- 编写一个简单的
HttpServer
返回json
数据
其中定义了2个结构体(json对象),需要注意可导出的结构体字段名必须大写,若需要返回的json中字段为小写,则需要增加别名,如定义响应码Code
Code int `json:"code"`
完整代码如下
package main
import(
"io"
"log"
"net/http"
"encoding/json"
"fmt"
)
type Data struct {
Name string `json:"name"`
Version string `json:"version"`
}
type Result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data Data `json:"data"`
}
func main() {
http.HandleFunc("/healthz",healthz)
http.HandleFunc("/get",get)
err := http.ListenAndServe(":80", nil)
if( err!= nil){
log.Fatal(err)
}
}
func healthz(w http.ResponseWriter, request *http.Request){
io.WriteString(w,"success")
}
func get(w http.ResponseWriter, request *http.Request){
w.Header().Set("content-type","application/json;charset=UTF-8")
data := Data{Name:"mixfate",Version:"1.0.0"}
result := Result{Code:200,Msg:"success",Data:data}
dataJson,_ := json.Marshal(result)
fmt.Println(string(dataJson))
io.WriteString(w,string(dataJson))
}
启动成功后可通过以下链接访问
http://192.168.1.11/get?name=mixfate
http://192.168.1.11/healthz