Net/HTTP and FASthTTP two HTTP protocol interface client implementation, the next is to start the development of the Server, do not learn not to know a surprise, surprisingly these two libraries also support the development of the Server, too convenient.

Compared to Java, HTTPServer development is basically using the Spring or Springboot framework, always configuring various configuration classes, various Handle objects. The Server development of Golang is very simple, because it is very simple, or there is no unified specification or framework. I have found many ways to implement it. The HTTP protocol is still based on NET/HTTP and FasthTTP, but the syntax of Handle is diverse.

First review: Golang HTTP client practice, Golang FasthTTP practice.

In terms of Golang language, there may be more libraries to achieve a certain function. If you have the opportunity, you still need to communicate with peers more, and you may find a better library. Below I’ll share a Demo of the six Server development implementations I’ve learned.

The first kind of

Implemented based on NET/HTTP, this is relatively basic and not elegant for interface and Handle mapping. Therefore, it is not recommended.

func TestHttpSer(t *testing.T) {
	server := http.Server{
		Addr: ": 8001",
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if strings.Index(r.URL.String(), "test") > 0 {
				fmt.Fprintf(w, "This is the first way to create a server for NET/HTTP")
				return
			}
			fmt.Fprintf(w, task.FunTester)
			return
		}),
	}
	server.ListenAndServe()
	log.Println("Start creating an HTTP service")}Copy the code

The second,

The second method is also based on NET/HTTP. This syntax can solve the problem of the first method very well. Handle and PATH have similar configuration syntax, which greatly improves readability.


type indexHandler struct {
	content string
}

func (ih *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, ih.content)
}

func TestHttpSer2(t *testing.T) {
	http.Handle("/test", &indexHandler{content: "This is the second net/ HTTP syntax for creating a service"})
	http.Handle("/", &indexHandler{content: task.FunTester})
	http.ListenAndServe(": 8001".nil)}Copy the code

The third kind of

The third is based on NET/HTTP and github.com/labstack/echo, the latter mainly provides Echo objects to handle various configurations including interfaces and Handle mappings, which are very rich and readable.

func TestHttpSer3(t *testing.T) {
	app := echo.New()
	app.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{echo.GET, echo.DELETE, echo.POST, echo.OPTIONS, echo.PUT, echo.HEAD},
		AllowHeaders: []string{echo.HeaderContentType, echo.HeaderAuthorization},
	}))
	app.Group("/test")
	{
		projectGroup := app.Group("/test")
		projectGroup.GET("/", PropertyAddHandler)
	}
	app.Server.Addr = ": 8001"
	gracehttp.Serve(app.Server)

}
Copy the code

A fourth

The fourth one is still implemented based on NET/HTTP and introduces the route of github.com/gin-gonic/gin. It seems that the mapping relationship between interface and Handle is relatively clear.

func TestHttpServer4(t *testing.T) {
	router := gin.New()

	api := router.Group("/okreplay/api")
	{
		api.POST("/submit", gin.HandlerFunc(func(context *gin.Context) {
			context.ShouldBindJSON(map[string]interface{} {"code": 0."msg":  "This is the fourth way to create HTTPServer.",
			})
			context.Status(200)
		}))

	}
	s := &http.Server{
		Addr:           ": 8001",
		Handler:        router,
		ReadTimeout:    1000 * time.Second,
		WriteTimeout:   1000 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}
Copy the code

The fifth

The fifth one is based on FasthTTP and uses the API provided by FasthTTP. It is readable, but handle configuration is more like Java.

func TestFastSer(t *testing.T) {
	address := ": 8001"
	handler := func(ctx *fasthttp.RequestCtx) {
		path := string(ctx.Path())
		switch path {
		case "/test":
			ctx.SetBody([]byte("This is the first syntax that FasthTTP uses to create a service."))
		default:
			ctx.SetBody([]byte(task.FunTester))
		}
	}
	s := &fasthttp.Server{
		Handler: handler,
		Name:    "FunTester server",}iferr := s.ListenAndServe(address); err ! = nil { log.Fatal("error in ListenAndServe", err.Error())
	}

}
Copy the code

6 kinds of

6 kinds of based on fasthttp, still use the github.com/buaazp/fasthttprouter, a bit surprised two is not a lot in the warehouse. Using grammar is similar to the third way, which is more organized and easier to read.

func TestFastSer2(t *testing.T) {
	address := ": 8001"

	router := fasthttprouter.New()
	router.GET("/test".func(ctx *fasthttp.RequestCtx) {
		ctx.Response.SetBody([]byte("This is the second syntax that FasthttP uses to create a server."))
	})
	router.GET("/".func(ctx *fasthttp.RequestCtx) {
		ctx.Response.SetBody([]byte(task.FunTester))
	})
	fasthttp.ListenAndServe(address, router.Handler)
}

Copy the code

Have Fun ~ Tester!

  • JMeter Chinese Operation Manual with a sense of time
  • 140 interview questions (UI, Linux, MySQL, API, security)
  • Graphic HTTP brain map
  • Share a Fiddler study bag
  • JVM command brain map for testing
  • The Definitive Guide to Java Performance
  • How do I choose the right test automation tool
  • Handle JMeter variables with Groovy
  • HTTP Interface Testing Basics
  • Functional and non-functional testing
  • How do I maintain automated tests
  • Jira API to step on the pit
  • Performance bottleneck tuning