做一个简单的通过http协议 server 和 client 交互样例。吧内帖子很多,但是没有一个完整的样例,在这里做一个摸索总结,希望对后来的学习go语言的小伙伴有帮助。
server端代码:
```go
package main
import (
"fmt"
"net/http"
)
func main() {
fmt.Println("server listening:")
http.HandleFunc("/con",conncet)
http.ListenAndServe(":8080",nil)
}
func conncet(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
data := r.URL.Query()
fmt.Println("all data", data)
var NameExist, IdExist bool
var Id,Name []string
if Id, NameExist = r.Form["Id"]; NameExist{
fmt.Println("Id is ",Id[0])
}
if Name, IdExist = r.Form["Name"]; IdExist{
fmt.Println("Name is ",Name[0])
}
if NameExist && IdExist{
w.Write([]byte(fmt.Sprintf("welcome %s to come in",Name[0])))
}
}
```
说明: server通过监听本地的8080端口,等待客户端的连接。先启动server,打印如下:
```
C:/Go\bin\go.exe run E:/go_code/gopath/src/example/http/httpserver.go
server listening:
all data map[Id:[321] Name:[agent]]
Id is 321
Name is agent
all data map[Name:[agent] Id:[321]]
Id is 321
Name is agent
```
client 代码,client 通过读取配置文件,获取服务的ip地址以及访问的目录地址。
```go
package main
import (
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
//"net/url"
)
type ServerInfo struct {
Ip string
Port string
Dir string
}
type ClientInfo struct {
Name string
ID string
}
type ConfigData struct {
ServerData ServerInfo
ClientData ClientInfo
}
func main() {
fmt.Println("client con:")
client := &http.Client{}
serveInst, clientInst, err := conInst.ServerData.GetServerInfoFromConf()
if err != nil{
fmt.Println(err)
return
}
url := serveInst.constructUrl()
urlpara := clientInst.constructUrl(&url)
req, e := http.NewRequest("Get",urlpara, nil)
if e !=nil{
fmt.Println(e)
}
//v := req.Form
//v.Set("Name",clientInst.Name)
//v.Set("Id",clientInst.ID)
rsp ,err1 := client.Do(req)
if err1 != nil{
fmt.Println("client Get err.",err1)
return
}
defer rsp.Body.Close()
data, err2 := ioutil.ReadAll(rsp.Body)
if err2 == nil {
fmt.Println(string(data))
}
fmt.Println("client over", err2)
}
var conInst = NewConfInfo()
func NewConfInfo() *ConfigData{
return &ConfigData{}
}
func (s *ServerInfo)GetServerInfoFromConf() (*ServerInfo, *ClientInfo,error){
conf := &ConfigData{}
data, err := ioutil.ReadFile("conf/info.json")
if err != nil{
fmt.Println("readdir failed, err is ",err)
return nil,nil,err
}
err1 := json.Unmarshal(data,conf)
if err1 != nil {
fmt.Println("unmarshal failed, err is ",err1)
return nil, nil,err1
}
fmt.Println("Get info is ",conf)
return &conf.ServerData, &conf.ClientData,nil
}
func (s *ServerInfo)constructUrl() string {
url := "http://" + s.Ip + ":" + s.Port + "/" + s.Dir
fmt.Println("url is",url)
return url
}
func (s *ClientInfo)constructUrl(url *string) string {
//*url =*url + "?" + "Name" + "=" + s.Name
*url =*url + "?" + "Name" + "=" + s.Name + "&"+ "Id" + "=" + s.ID
fmt.Println("url is", *url)
return *url
}
```
clinet 打印如下:
```
C:/Go\bin\go.exe run E:/go_code/gopath/src/example/http/httpclient.go
client con:
Get info is &{{127.0.0.1 8080 con} {agent 321}}
url is http://127.0.0.1:8080/con
url is http://127.0.0.1:8080/con?Name=agent&Id=321
welcome agent to come in
client over <nil>
Process finished with exit code 0
```
json文件如下:
```json
{
"ServerData" :{
"Ip" : "127.0.0.1",
"Port": "8080",
"Dir" : "con"
},
"ClientData" :{
"Name": "agent",
"ID": "321"
}
}
```
有疑问加站长微信联系(非本文作者))
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)