温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Go语言HTTPServer开发的有那几种方式

发布时间:2021-11-03 13:32:54 来源:亿速云 阅读:135 作者:iii 栏目:开发技术

这篇文章主要介绍“Go语言HTTPServer开发的有那几种方式”,在日常操作中,相信很多人在Go语言HTTPServer开发的有那几种方式问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Go语言HTTPServer开发的有那几种方式”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

第一种

基于net/http实现,这是一种比较基础的,对于接口和handle映射关系处理并不优雅,不推荐使用。

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, "这是net/http创建的server第一种方式")
    return
    }
    fmt.Fprintf(w, task.FunTester)
    return
  }),
  }
  server.ListenAndServe()
  log.Println("开始创建HTTP服务")
}

第二种

第二种也是基于net/http,这种编写语法可以很好地解决第一种的问题,handle和path有了类似配置的语法,可读性提高了很多。

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: "这是net/http第二种创建服务语法"})
  http.Handle("/", &indexHandler{content: task.FunTester})
  http.ListenAndServe(":8001", nil)
}

第三种

第三个基于net/http和github.com/labstack/echo,后者主要提供了Echo对象用来处理各类配置包括接口和handle映射,功能很丰富,可读性最佳。

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)
}

第四种

第四种依然基于net/http实现,引入了github.com/gin-gonic/gin的路由,看起来接口和handle映射关系比较明晰了。

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":  "这是创建HTTPServer第四种方式",
    })
    context.Status(200)
  }))
  }
  s := &http.Server{
  Addr:           ":8001",
  Handler:        router,
  ReadTimeout:    1000 * time.Second,
  WriteTimeout:   1000 * time.Second,
  MaxHeaderBytes: 1 << 20,
  }
  s.ListenAndServe()
}

第五种

第五种基于fasthttp开发,使用都是fasthttp提供的API,可读性尚可,handle配置倒是更像Java了。

func TestFastSer(t *testing.T) {
  address := ":8001"
  handler := func(ctx *fasthttp.RequestCtx) {
  path := string(ctx.Path())
  switch path {
  case "/test":
    ctx.SetBody([]byte("这是fasthttp创建服务的第一种语法"))
  default:
    ctx.SetBody([]byte(task.FunTester))
  }
  }
  s := &fasthttp.Server{
  Handler: handler,
  Name:    "FunTester server",
  }
  if err := s.ListenAndServe(address); err != nil {
  log.Fatal("error in ListenAndServe", err.Error())
  }
}

第六种

第六种依然基于fasthttp,用到了github.com/buaazp/fasthttprouter,有点奇怪两个居然不在一个GitHub仓库里。使用语法跟第三种方式有点类似,比较有条理,有利于阅读。

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


  router := fasthttprouter.New()
  router.GET("/test", func(ctx *fasthttp.RequestCtx) {
  ctx.Response.SetBody([]byte("这是fasthttp创建server的第二种语法"))
  })
  router.GET("/", func(ctx *fasthttp.RequestCtx) {
  ctx.Response.SetBody([]byte(task.FunTester))
  })
  fasthttp.ListenAndServe(address, router.Handler)
}

到此,关于“Go语言HTTPServer开发的有那几种方式”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI