fasthttp-test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/buaazp/fasthttprouter"
  5. "github.com/valyala/fasthttp"
  6. "log"
  7. )
  8. // index 页
  9. func Index(ctx *fasthttp.RequestCtx) {
  10. ctx.Request.Header.Peek("userid")//获取header头参数
  11. fmt.Fprint(ctx, "Welcome")
  12. }
  13. // 简单路由页
  14. func Hello2(ctx *fasthttp.RequestCtx) {
  15. name:= ctx.UserValue("name").(string) //获取路由参数name
  16. fmt.Fprintf(ctx, "hello,%s",name)
  17. }
  18. // 获取GET请求json数据
  19. func TestGet(ctx *fasthttp.RequestCtx) {
  20. values := ctx.QueryArgs() // 使用 ctx.QueryArgs() 方法
  21. fmt.Fprint(ctx, string(values.Peek("abc"))) // 不加string返回的byte数组
  22. fmt.Fprint(ctx, string(ctx.FormValue("abc"))) // 获取表单数据
  23. }
  24. // 获取post的请求json数据
  25. func TestPost(ctx *fasthttp.RequestCtx) {
  26. postBody := ctx.PostBody() // 这两行可以获取PostBody数据,文件上传也有用
  27. fmt.Fprint(ctx, string(postBody))
  28. fmt.Fprint(ctx, string(ctx.FormValue("abc"))) // 获取表单数据
  29. }
  30. func main() {
  31. // 创建路由
  32. router := fasthttprouter.New()
  33. // 不同的路由执行不同的处理函数
  34. router.GET("/", Index)
  35. router.GET("/hello/:name", Hello2)
  36. router.GET("/get", TestGet)
  37. // post方法
  38. router.POST("/post", TestPost)
  39. // 启动web服务器,监听 0.0.0.0:80
  40. log.Fatal(fasthttp.ListenAndServe("0.0.0.0:10087", router.Handler))
  41. }