go 入门级 一个http服务

ServeMux 是go自带的http请求处理器,是一个路由表,存放key-value。根据请求路径(key)在路由表中查找,(按照最长匹配原则)并将请求交给对应的处理函数(value).

导入http包,介绍几个方法:

  1. http.ListenAndServe (addr string, handler Handler) //传入请求路径和路由表的handler
    
  2. handler :=http.NewServeMux()  //创建 一个路由表的handler
  3. handler.HandleFunc("/api/", handle_func)//注册路由表,HandleFunc会将函数转为实现了ServeHTTP接口的新类型,但是需要保证传入的handle_func是符合 func(ResponseWriter,*Request)类型的。

上代码啦:

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

func requ(w http.ResponseWriter, r *http.Request){
	fmt.Println(r.Body)
	fmt.Println(r.Header)
	resp :=map[string]interface{}{"status": 0, "msg": "ok", "data": "get it!"}
	rr,_ := json.Marshal(resp)
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusBadRequest)
	w.Write(rr)
}
func print_hello(w http.ResponseWriter, r *http.Request){
	resp :=map[string]interface{}{"data": "hello !"}
	rr,_ := json.Marshal(resp)
	w.WriteHeader(http.StatusOK)
	w.Write(rr)
}
func main(){
	address :="127.0.0.1:8080"
	mux:=http.NewServeMux()
	mux.HandleFunc("/", requ)
	mux.HandleFunc("/api/hi/",print_hello)
	//HandleFunc(pattern string, handler func(ResponseWriter, *Request))
	http.ListenAndServe(address, mux)
	//func ListenAndServe(addr string, handler Handler) error
}

现在在入门级基础上 加一下东西,判断请求的方法,和拿到请求中body体,上代码:

//server 端
func requ(w http.ResponseWriter, r *http.Request){
      if r.Method!="POST"{
		resp :=map[string]interface{}{"status": -1, "msg": "请求方法错误", "data": ""}
		rr,_ := json.Marshal(resp)
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusBadRequest)
		w.Write(rr)
		return 
	}
	body := make([]byte, r.ContentLength)
	r.Body.Read(body)
	//fmt.Println(body)
	var data interface{}
	err:=json.Unmarshal(body,&data)
	//解析失败会报错,如json字符串格式不对,缺"号,缺}等。
	if err!=nil{
		fmt.Println(err)
	}
    fmt.Println(data)//获取到的就是body体内容
    //对于请求给出响应 
	resp :=map[string]interface{}{"status": 0, "msg": "ok", "data": "get it!"}
	rr,_ := json.Marshal(resp)
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	w.Write(rr)
    
}
func print_hello(w http.ResponseWriter, r *http.Request){
	resp :=map[string]interface{}{"data": "hello !"}
	rr,_ := json.Marshal(resp)
	w.WriteHeader(http.StatusOK)
	w.Write(rr)
}
func main(){
	address :="127.0.0.1:8080"
	http.HandleFunc("/", requ)
	http.HandleFunc("/api/hi/",print_hello)
	//HandleFunc(pattern string, handler func(ResponseWriter, *Request))
	http.ListenAndServe(address, nil)
	//func ListenAndServe(addr string, handler Handler) error
}


// client 端

func Post(url string, data interface{}, contentType string)  {
    
	// 超时时间:5秒
	client := &http.Client{}
	jsonStr, _ := json.Marshal(data)
	fmt.Println(jsonStr)
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode==200{
		fmt.Println("调用成功")
    //或者可以处理服务端返回的数据
    result, _ := ioutil.ReadAll(resp.Body)
	fmt.Pringln( string(result))
	}

	
}

func main() {
    url:="http://127.0.0.1:8080"
	var data map[int]string=map[int]string{1:"chen",2:"tian"}
	fmt.Println(Post(url,data,"application/json"))

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值