您的位置 首页 golang

Golang 基础代码 – web 服务

Golang 基础包 net/http 不依赖第三方包实现web服务

Golang test 进行性能测试,指定时间内进行性能测试

 go test -bench='Query$' -benchtime=5s .  

main.go

 package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)
type ReqBody struct {
	Ids []int
	Sn  int
}
type RespBody struct {
	Sn int
	Id int
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	var p ReqBody

	err := json.NewDecoder(r.Body).Decode(&p)

	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	resp := &RespBody{p.Sn, majorityElement(p.Ids)}

	json.NewEncoder(w).Encode(resp)
}

//摩尔投票法(Boyer–Moore majority vote algorithm)会比简单的Map等方式在时间O(n)、空间O(1)复杂度方面优势
func majorityElement(nums []int) int {
	count := 0
	restult := 0
	for _, num := range nums {
		if count == 0 {
			restult = num
		}
		if num == restult {
			count++
		} else {
			count--
		}
	}
	return restult
}

func main() {
	http.HandleFunc("/api/vote", handleRequest)
	fmt.Println("ListenAndServe...10000")
	log.Fatal(http.ListenAndServe(":10000", nil))
}  

main_test.go

 // Author: 码农漫步人生路
// Date: 2021-06-28
//
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"testing"
)

// go test -bench='Query$' -benchtime=5s .
// 服务性能测试,mac笔记本 BenchmarkQuery-12    	   13461	     88323 ns/op
func BenchmarkQuery(b *testing.B) {

	ids := []int{1, 3, 3,2,3,3,4}

	if requestVote(ids,121).Id !=3 {
		b.Error("Not equals 3")
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		requestVote(ids,139)
	}
}


func requestVote(ids []int,sn int)  RespBody{

	reqBody := &ReqBody{ids,sn}

	rb,_:=json.Marshal(reqBody)

	resp,err := http.Post("#34;,"application/json",bytes.NewBuffer(rb))

	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Println("response Status:", resp.Status)
		fmt.Println("response Headers:", resp.Header)
	}
	body, _ := ioutil.ReadAll(resp.Body)

	var respBody RespBody

	json.Unmarshal(body,&respBody)

	return respBody
}  

go.mod

 module github.com/vote

go 1.14  

文章来源:智云一二三科技

文章标题:Golang 基础代码 – web 服务

文章地址:https://www.zhihuclub.com/97880.shtml

关于作者: 智云科技

热门文章

网站地图