Golang小白,自学搭建简易web服务器,有何不妥当之处,望请大佬指正
目录
客户端:发送简单json请求给服务器
服务器:连接客户端,解析json,将内容发布到web
客户端:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
type person struct {
Company string `json:"company"`
Subject []string `json:"sub"`
Isok bool `json:",string"`
Price float64 `json:",string"`
}
func main() {
tmp := person{"csj", []string{"Go", "java", "python"}, true, 13.14}
data, err := json.Marshal(tmp) //转化为JSON
if err != nil {
fmt.Println("json Marshal err", err)
}
resp, err := http.Post("http://127.0.0.1:8001/test", "application/x-www-form-urlencoded", strings.NewReader(string(data)))
fmt.Println(data)
fmt.Println(string(data))
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) //读取服务器返回的信息
if err != nil {
fmt.Println("read err")
}
fmt.Println(string(body))
}
服务器:
package main
import (
"fmt"
"io/ioutil"
"os"
"net/http"
"encoding/json"
"io"
"strconv"
)
type person struct {
Company string `json:"company"` //二次编码,使名字变为company1
Subject []string `json:"sub"` //- 此字段不输出在屏幕上
Isok bool `json:",string"` //使其变成字符串类型
Price float64 `json:",string"` //使其变成字符串类型
}
func main() {
http.HandleFunc("/test", handler)
err := http.ListenAndServe("127.0.0.1:8001", nil)
if err != nil {
fmt.Println("err")
}
}
func WriteFile(body []byte){ //将客户端请求存储到文件
FileName:="./test1.txt"
f,err:=os.Create(FileName)
if err!=nil{
fmt.Println("os.create err = ",err)
return
}
defer f.Close()
n,err:=f.Write(body)
if err!=nil{
fmt.Println("f.write err = ",err)
return
}
fmt.Println("n =",n)
}
func ReadFile()(body2 []byte){
f,err:=os.Open("./test1.txt")
defer f.Close()
if err!=nil{
fmt.Println("openfile err = ",err)
return
}
body2=make([]byte,1024*4) //
var n1 int
if f!=nil{
fmt.Println("文件不为空")
n1,err=f.Read(body2)
fmt.Println("n1=?",n1)
if err != nil && err != io.EOF { //文件出错,但没有到结尾
fmt.Println("err =", err)
return
}
body2=body2[:n1] //取出对应长度数据
}
fmt.Println(body2)
return body2
}
func handler(w http.ResponseWriter, r *http.Request) {
var bodyC string
fmt.Println("ok")
w.Write([]byte("connect ok "))
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("read err")
}
fmt.Println(body)
bodyC=string(body)
if bodyC!=""{
WriteFile(body) //将客户端的请求存储到文件
}
body2:=ReadFile() //将文件内容读取
tmp := person{}
err = json.Unmarshal(body2, &tmp) //JSON还原
if err != nil {
fmt.Println("unmarshal err")
}
w.Write([]byte(tmp.Company+" "))
l:=len(tmp.Subject) //获取subject切片长度
for i:=0;i<l;i++{
w.Write([]byte(tmp.Subject[i]+" "))
}
w.Write([]byte(strconv.FormatBool(tmp.Isok)+" ")) //转换成字符串形式
w.Write([]byte(strconv.FormatFloat(tmp.Price,'f',2,64)+" ")) //转换成字符串形式
fmt.Println(tmp)
}