搭建一个http服务

go搭建一个服务器

需求分析

1.实现接口
2.获取请求方式
3.超时处理
4.返回url,请求方式
5.自定义404
6.返回json

返回体的

//返回结构体
type JsonRes struct {
	Code      int         `json:"code"`
	Data      interface{} `json:"data"`
	Msg       string      `json:"msg"`
	TimeStamp int64       `json:"timestmap"`
}

返回json方法

//返回json方法
func apiResult(w http.ResponseWriter, code int, data interface{}, msg string) {
	body, _ := json.Marshal(JsonRes{
		Code: code,
		Data: data,
		Msg:  msg,
		//获取时间戳
		TimeStamp: time.Now().Unix(),
	})
	w.Write(body)
}

获取参数

//处理并接受数据 输出 json
func sayHello(w http.ResponseWriter, r *http.Request) {
	//获取请求数据
	query := r.URL.Query()
	//第一种方式 获取参数 name 参数没有会报错
	//name := query["name"][0]
	// 第二种方式
	name := query.Get("name")

	apiResult(w, 0, name+" say "+r.PostFormValue("some"), "success")
}

路由方法

func defaultHttp(w http.ResponseWriter, r *http.Request) {
	path, httpMethod := r.URL.Path, r.Method

	if path == "/" {
		w.Write([]byte("indexs"))
		return
	}

	if path == "/hello" && httpMethod == "POST" {
		sayHello(w, r)
		return
	}

	if path == "/sleep" {
		//模拟一下业务处理超时
		time.Sleep(4 * time.Second)
		return
	}
	//获取请求方式
	if path == "/path" {
		w.Write([]byte("path:" + path + ",method:" + httpMethod))
		return
	}

	//自定义404
	http.Error(w, "you lost???", http.StatusNotFound)
}

主方法

func main() {
	srv := http.Server{
		Addr:    ":88",
		Handler: http.TimeoutHandler(http.HandlerFunc(defaultHttp), 2*time.Second, "Timeout!!!"),
	}
	srv.ListenAndServe()
}
posted @ 2021-07-08 16:53  野香蕉  阅读(158)  评论(0)    收藏  举报