Giter Site home page Giter Site logo

hertz-examples's Introduction

Hertz Examples

English | 中文

How to run

You can enter the example for information about "How to run"

Bizdemo

Server

  • hello: Example of launching a hertz "hello world" application
  • config: Example of configuring hertz server
  • protocol: Example of using http1, tls and other protocols of hertz
    • HTTP1 Example of hertz using HTTP1 protocol
    • TLS Example of hertz using TLS protocol
    • HTTP2 Example of hertz using HTTP2 protocol
    • HTTP3 Example of hertz using HTTP3 protocol
    • Websocket Example of hertz using Websocket protocol
    • SSE Example of hertz using SSE protocol
  • middleware: Example of using middleware of hertz
    • basicauth: Example of using BasicAuth middleware
    • cors: Example of using CORS middleware
    • csrf: Example of using csrf middleware
    • custom: Example of using custom middleware
    • pprof: Example of using pprof middleware
    • requestid: Example of using RequestID middleware
    • gzip: Example of using Gzip middleware
    • loadbalance: Example of using Loadbalance middleware
    • Recovery Example of using Recovery middleware
    • jwt Example of using jwt middleware
    • i18n Example of using i18n middleware
    • session Example of using session middleware
    • KeyAuth Example of using KeyAuth middleware
    • Swagger Example of using Swagger middleware
    • access log Example of using access log middleware
    • Secure Example of using Secure middleware
    • Sentry Example of using Sentry middleware
    • Casbin Example of using Casbin middleware
    • ETag Example of using ETag middleware
    • Cache Example of using Cache middleware
    • Paseto Example of using Paseto middleware
  • binding: Example of parameter binding and validation
  • parameters: Example of getting query, form, cookie
  • file: Examples of file upload, file download, and static file services
  • render: Example of render body as json, html, protobuf
  • redirect: Examples of redirects to internal/external URI
  • streaming: Example of streaming read/write for hertz server
  • graceful_shutdown: Example of a graceful shutdown for hertz server
  • unit_test: Example of writing unit tests using the interface provided by hertz without network transmission
  • tracer: Example of using Jaeger for link tracing
  • monitoring: Example of using Prometheus for metrics monitoring
  • multiple_service: Example of using hertz with multiple services
  • adaptor: Example of using adaptor to integrate hertz with package built for http.Handler interface , including a demonstration on using jade as template engine.
  • sentinel: Example of using sentinel-golang in hertz
  • reverseproxy: Example of using reverseproxy in hertz server
  • gzip: Example of using gzip middleware in hertz server
  • hlog: Example of using hlog and its log extension
  • trailer: Example of read/write trailers for hertz server
  • graphql-go: Example of using graphql in hertz server

Client

Hz

  • hz/thrift: Example of using hz with thrift to generate server code
  • hz/protobuf: Example of using hz with protobuf to generate server code
  • hz/hz_client: Example of using hz to generate client code
  • hz/template: Example of using hz custom templates to generate server code
  • hz/plugin: Example of using hz to access third-party plugins
  • hz/struct_reuse: Example of using hz to use kitex_gen as hertz model

Note

All commands to execute the example should be executed under "hertz-example".

hertz-examples's People

Contributors

ansidev avatar baize1998 avatar chaoranz758 avatar chenghonour avatar claude-zq avatar coderpoet avatar cqqqq777 avatar dependabot[bot] avatar fgyffff avatar guangmingluo avatar hanser001 avatar haswf avatar justlorain avatar l2nce avatar leeeezp avatar li-jin-gou avatar nihilism0 avatar pedroamc avatar powerxu519 avatar purewhitewu avatar rogerogers avatar skyenought avatar stellarisw avatar sujit-baniya avatar towelong avatar violapioggia avatar wzekin avatar xiaoyi-byte avatar yuandjiang avatar zstone12 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hertz-examples's Issues

For rendering, any features to do header.tmpl / footer. tmpl etc?

i realised ctx.HTML is much slower than ctx.String... possible to speed this up? 50k req/s vs 15k req/s

For rendering, any features to do header.tmpl / footer. tmpl etc?

for header and footer so to have consistency. just curious how to stack them together. now i'm doing a lot of repeats. how to stack them together?

                ctx.HTML(consts.StatusOK, "index.tmpl", utils.H{
                        "t": "Main website",
                        "h": "Head website",
                        "b": "Body website",
                })

hz 集成 protoc-gen-openapi 插件报错

Describe the Question

img_v3_02a3_64145d6d-a9ff-4b76-8777-8d9b4680a9cg
按照这个示例生成文档时报错,
plugin protoc_gen_hertz returns error: exit status 1, cause:
openapiv3/annotations.proto: File not found.
google/api/annotations.proto: File not found.

Expected behavior

怎么才能导入 openapiv3/annotations.proto 和 google/api/annotations.proto

Hertz version:

v0.8.1

Environment:

go1.22.2

Example optimization

There is a conflict between the processing function used in the example and the source code. Will it be optimized later

登录的时候使用jwt的插件,如果参数名字不对返回307,使用postman请求时返回404,其次设置content-type=text/html,返回结果为text/plain格式

Describe the bug

A clear and concise description of what the bug is.

To Reproduce

Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Hertz version:

Please provide the version of Hertz you are using.

Environment:

The output of go env.

Additional context

Add any other context about the problem here.

运行example下的示例报错

我通过 git 下载了 example 项目,在 hello 目录下,运行 go run main.go 时,报了如下的错误,我的运行环境是 Win10。
在运行example项目之前, 还运行了文档中的快速开始。用 hz new 创建了一个快速开始的项目,并且运行成功。
7591eb485e0346c752c22b4a34a1fa5

参数验证功能咨询

Describe the bug
我参照hertz文档写了一段代码,一个小型服务,但是参数验证始终存在问题。下面是我的代码:

package main

import (
	"context"
	"github.com/cloudwego/hertz/pkg/app/server/binding"
	"github.com/cloudwego/hertz/pkg/common/hlog"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

type BindError struct {
	ErrType, FailField, Msg string
}

// Error implements error interface.
func (e *BindError) Error() string {
	if e.Msg != "" {
		return e.ErrType + ": expr_path=" + e.FailField + ", cause=" + e.Msg
	}
	return e.ErrType + ": expr_path=" + e.FailField + ", cause=invalid"
}

type ValidateError struct {
	ErrType, FailField, Msg string
}

// Error implements error interface.
func (e *ValidateError) Error() string {
	if e.Msg != "" {
		return e.ErrType + ": expr_path=" + e.FailField + ", cause=" + e.Msg
	}
	return e.ErrType + ": expr_path=" + e.FailField + ", cause=invalid"
}

func init() {
	CustomBindErrFunc := func(failField, msg string) error {
		err := BindError{
			ErrType:   "bindErr",
			FailField: "[bindFailField]: " + failField,
			Msg:       "[参数接收失败]: " + msg,
		}

		return &err
	}

	CustomValidateErrFunc := func(failField, msg string) error {
		err := ValidateError{
			ErrType:   "validateErr",
			FailField: "[validateFailField]: " + failField,
			Msg:       "[参数验证失败]: " + msg,
		}

		return &err
	}

	binding.SetErrorFactory(CustomBindErrFunc, CustomValidateErrFunc)
}

type LoginInput struct {
	UserName   string `json:"userName,required" vd:"regexp('[a-zA-Z0-9_-]{4,50}$'); msg:'账号格式错误'"`
	Password   string `json:"password,required"`
	Captcha    string `json:"captcha,required" vd:"len($)==4; msg:'验证码字符数量不正确'"`
	ClientType int    `json:"clientType,required" vd:"$==1||$==2||$==3||$==4; msg:'客户端类型无效'"`
}

func main() {
	h := server.Default()

	h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
		ctx.JSON(consts.StatusOK, utils.H{"msg": "pong"})
	})

	h.POST("/login", func(c context.Context, ctx *app.RequestContext) {
		var req LoginInput
		if err := ctx.BindAndValidate(&req); err != nil {
			hlog.CtxErrorf(c, "登录参数验证失败:%+v", err)
			ctx.JSON(consts.StatusBadRequest, utils.H{"msg": err.Error()})
			return
		}
		hlog.CtxInfof(c, "登录,参数:%+v", req)
		ctx.JSON(consts.StatusOK, utils.H{"msg": "login success", "data": req})
	})

	h.Spin()
}

To Reproduce

  1. 请求curl -X POST -d '{"userName":"z","password":"123456","captcha":"1234","clientType":-1}' -H 'Content-Type:application/json' localhost:8888/login,返回{"msg":"validateErr: expr_path=[validateFailField]: UserName, cause=[参数验证失败]: 账号格式错误"}这个是符合预期的
  2. 请求$ curl -X POST -d '{"userName":"z","password":"123456","captcha":"1234"}' -H 'Content-Type:application/json' localhost:8888/login,返回{"msg":"bindErr: expr_path=[bindFailField]: clientType, cause=[参数接收失败]: missing required parameter"}

Expected behavior

当我在struct中定义了json的tag和vd之后,vd的校验没问题了,可是json的tag中的required对应的提示消息上哪里去自定义呢?

Hertz version:

v0.4.2

我的gomod

module hertz_demo

go 1.19

require github.com/cloudwego/hertz v0.4.2

require (
	github.com/bytedance/go-tagexpr/v2 v2.9.2 // indirect
	github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7 // indirect
	github.com/bytedance/sonic v1.5.0 // indirect
	github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06 // indirect
	github.com/cloudwego/netpoll v0.3.1 // indirect
	github.com/fsnotify/fsnotify v1.5.4 // indirect
	github.com/golang/protobuf v1.5.0 // indirect
	github.com/henrylee2cn/ameda v1.4.10 // indirect
	github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8 // indirect
	github.com/klauspost/cpuid/v2 v2.0.9 // indirect
	github.com/nyaruka/phonenumbers v1.0.55 // indirect
	github.com/tidwall/gjson v1.13.0 // indirect
	github.com/tidwall/match v1.1.1 // indirect
	github.com/tidwall/pretty v1.2.0 // indirect
	github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
	golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
	golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect
	google.golang.org/protobuf v1.27.1 // indirect
)

Environment:

set GO111MODULE=on
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\lidawei\AppData\Local\go-build
set GOENV=C:\Users\lidawei\AppData\Roaming\go\env
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\lidawei\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\lidawei\go
set GOPRIVATE=
set GOPROXY=https://goproxy.cn
set GOROOT=C:\Program Files\Go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=C:\Program Files\Go\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.19.2
set GCCGO=gccgo
set GOAMD64=v1
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=E:\code\GoglandProjects\hertz_demo\go.mod
set GOWORK=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -Wl,--no-gc-sections -fmessage-length=0 -fdebug-prefix-map=C:\Users\lidawei\AppData\Local\Temp\go-build1957160079=/tmp/go-build -gno-record-gcc-switches
PS E:\code\GoglandProjects\hertz_demo>

Additional context

我重点想验证hertz与go-tagexpr整合在一起的时候的强大的参数验证功能,但是认真地讲,文档和资料不太齐全,示例也不够生动,费了好大劲,终于弄明白了基本用法,但是对于required的提示消息,仍然不知道上哪里去自定义。

opentelementry的示例问题

用wsl2建立了docker-compose.yml和otel-collector-config.yaml运行之后,有一个容器:opentelemetry-collector一直运行不起来

示例:
image

本地建立yaml文件:
image

docker运行:
image

报错日志:
image
看日志的意思好像是opentelemetry-collector 支持的export中不含有jaeger,有效的是这些:(valid values: [skywalking sumologic dynatrace prometheusremotewrite sapm tanzuobservability prometheus awscloudwatchlogs carbon f5cloud googlemanagedprometheus influxdb otlp otlphttp clickhouse datadog instana loadbalancing loki opencensus logging splunk_hec tencentcloud_logservice parquet awsxray azuremonitor cassandra googlecloudpubsub zipkin awss3 file logicmonitor signalfx coralogix azuredataexplorer elasticsearch googlecloud pulsar sentry alibabacloud_logservice awskinesis dataset kafka logzio mezmo awsemf])

定位到otel-collector-config.yaml中的配置:
image
里面指定的exporters确实指定了jaeger

问题猜测:
是不是版本问题,otel-collector的最新版本中exporters不支持jaeger了?

如何在同时生成http和rpc服务时,调用自定义代码模版

我现在想自定义代码生成模版,项目结构采用DDD的分层设计,但是我使用
cwgo server --idl idl/hello.thrift --service p.s.m --hex --module cw --template tpl
这个命令生成代码时提示
[ERROR]/Users/ruler/go/pkg/mod/github.com/cloudwego/hertz/cmd/[email protected]/thrift/plugin.go:158: generate package failed: init layout config failed, err: read layout config from tpl/package.yaml failed, err: open tpl/package.yaml: no such file or directory
也就是--template 只能选择http和Rpc其中一个模版,没法直接使用两个模版进行代码创建。
请问这个要怎么处理呢

使用hertz 进行302重定向

nauthorized: func(ctx context.Context, c *app.RequestContext, code int, message string) {
			hlog.CtxErrorf(ctx, "Unauthorized = %+v", code)
			c.Redirect(http.StatusFound, []byte("/login"))
			c.SetContentType("text/html; charset=utf-8")
			//c.Header("Refresh", "0;url=https://www.xpybz.top/login")
			//c.String(http.StatusTemporaryRedirect, "message:%+v", message)
		},

登录失败返回302给浏览器,浏览器收到请求后地址栏没有变,页面也没有跳到登录页面
是我的设置有问题吗

how to set response header easily?

how to set response header easily?

i know ctx.HTML() sets content type html but how do i override c.String() coz i want output as text/html

cant seemed to get reverse proxy working with nginx https backend

@li-jin-gou there's a domain name for the nginx-fcgi-php, no matter what i've done, it doesnt seem to recognize the https backend with response.

2024/05/01 07:21:14.187199 engine.go:469: [Error] HERTZ: Error=remote error: tls: unknown certificate, remoteAddr=172.17.0.1:39776

can anyone help? i've tried commenting and uncommenting the below etc. it's tested inside docker. shld work wherever but not working.

package main

import (
        //"context"
        "crypto/tls"
        "fmt"
        //"sync"

        //"github.com/cloudwego/hertz/pkg/app"
        "github.com/cloudwego/hertz/pkg/app/client"
        "github.com/cloudwego/hertz/pkg/app/server"
        "github.com/cloudwego/hertz/pkg/protocol"
        //"github.com/cloudwego/hertz/pkg/common/utils"
        //"github.com/cloudwego/hertz/pkg/app/middlewares/client/sd"
        "github.com/cloudwego/hertz/pkg/common/config"
        "github.com/cloudwego/hertz/pkg/network/standard"
        "github.com/hertz-contrib/reverseproxy"
        //"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
                cfg := &tls.Config{
                        MinVersion:               tls.VersionTLS12,
                        //CurvePreferences:         []tls.CurveID{tls.X25519, tls.CurveP256},
                        //PreferServerCipherSuites: true,
                        /*
                        CipherSuites: []uint16{
                                tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
                                tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
                                tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                        },
                        */
                }
                cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
                if err != nil {
                        fmt.Println(err.Error())
                }
                cfg.Certificates = append(cfg.Certificates, cert)

                h := server.New(
                        server.WithHostPorts(":443"),
                        server.WithTLS(cfg),
                )

                proxy, err := reverseproxy.NewSingleHostReverseProxy("https://172.17.0.4:443",
                        client.WithTLSConfig(&tls.Config{
                                InsecureSkipVerify: true,
                        }),
                        client.WithDialer(standard.NewDialer()),
                )
                if err != nil {
                        panic(err)
                }
        proxy.SetDirector(func(req *protocol.Request) {
                req.SetRequestURI(string(reverseproxy.JoinURLPath(req, proxy.Target)))
                req.Header.SetHostBytes(req.URI().Host())
                req.Options().Apply([]config.RequestOption{config.WithSD(true)})
        })
                h.Any("/", proxy.ServeHTTP)

                /*
        h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
                ctx.String(consts.StatusOK, "TLS test\n")
        })
        */

                h.Spin()

}

按照README步骤client无法生成example的代码

Describe the bug

hz client 无法生成example类似代码

To Reproduce

Steps to reproduce the behavior:

因为项目不在GOPATH的src下,所以就只比README中示例多了一个 --module 的option

image

生成了以上的代码,明显Client没有main.go文件,也没有go.mod文件

我尝试重新创建client目录并先创建go.mod,还是生成一样的代码

image

试试go run .

server没问题
image

client显然有问题:

image

Expected behavior

生成example的代码

Hertz version:

image

Environment:

set GO111MODULE=on
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\Ambrose\AppData\Local\go-build
set GOENV=C:\Users\Ambrose\AppData\Roaming\go\env
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\Ambrose\sdk\go1.19.1\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\Ambrose\sdk\go1.19.1;C:\Users\Ambrose\sdk\go1.19.1\bin
set GOPRIVATE=
set GOPROXY=https://goproxy.cn,direct
set GOROOT=C:\Users\Ambrose\sdk\go1.19.1
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=C:\Users\Ambrose\sdk\go1.19.1\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.19.1
set GCCGO=gccgo
set GOAMD64=v1
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=0
set GOMOD=C:\Users\Ambrose\GolandProjects\HertzDemo\client\go.mod
set GOWORK=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -fno-caret-diagnostics -Qunused-arguments -Wl,--no-gc-sections -fmessage-length=0 -fdebug-prefix-map=C:\Users\Ambrose\AppData\Local\Temp\go-build595009250=/tmp/go-build -gno-record-gcc-switches

hz_kitex_demo queryStudent API not work

Describe the bug

Query Student with student Num failed.

To Reproduce

Steps to reproduce the behavior:

  1. Insert two or more students (range from 1 to n) into backend with
    insertStudent API in postman.
  2. Query the first Student with req.Num = 1 using queryStudent API in postman.
  3. Query the second Student with req.Num = 2 using queryStudent API in postman.
  4. See Query failure with req.Num >= 2 in postman.

Expected behavior

The students we insert previously could be successfully retrieved by
queryStudent API.

Screenshots

N/A

Hertz version:

v0.4.0

Environment:

The output of go env:
GO111MODULE=""
GOARCH="arm64"
GOBIN=""
GOCACHE="/Users/danielwong/Library/Caches/go-build"
GOENV="/Users/danielwong/Library/Application Support/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="arm64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/danielwong/Dev/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/danielwong/Dev/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/opt/homebrew/Cellar/go/1.19.2/libexec"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/opt/homebrew/Cellar/go/1.19.2/libexec/pkg/tool/darwin_arm64"
GOVCS=""
GOVERSION="go1.19.2"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/danielwong/Dev///go.mod"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments
-fmessage-length=0
-fdebug-prefix-map=/var/folders/ql/05dw_j5x4pg52d5dfl4kbqgr0000gn/T/go-build2203124406=/tmp/go-build
-gno-record-gcc-switches -fno-common"

Additional context

The problem is because we defined the Student Num as a string, but did
validation as an integer.
see "/idl/student_api.thrift":
struct QueryStudentRequest {
1: string Num (api.query="num", api.vd="$<100; msg:'num must less than
100'");
// 学号,通过query参数进行绑定
}

hertz里面基于http怎么发送 x-protobuf格式的请求以及接收的时候BindAndValidate怎么写呢

Is your feature request related to a problem? Please describe.

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like

A clear and concise description of what you want to happen.

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Additional context

Add any other context or screenshots about the feature request here.

为什么使用otel实现链路追踪是http server调用 rpc client总是并列关系,而不是层次关系?

首先,我使用cwgo工具生成了api server服务与rpc server和rpc client服务,然后docker 运行了jaeger-all-in-one环境。
其次,参考本仓库的openTelemetry扩展配置链路追踪。

具体配置如下:

api server :
image

rpc server:
image

rpc client:
image

完成上述配置后向接口发送一次请求,jaeger UI的query如下:

image

我是在http的service层调用的rpc client获取数据,按照这个逻辑,应该是分层次的,类似于这样:

user-http-server
|——user-rpc-server

请问是那个地方配置错了,还是我理解错了,需要怎样配置或者使用才能达到此仓库的图片显示的那样有参差的记录。希望能得到解答,谢谢!

cors

Is your feature request related to a problem? Please describe.

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like

A clear and concise description of what you want to happen.

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Additional context

Add any other context or screenshots about the feature request here.

POST http://localhost:5173/api/route_name 500 (Internal Server Error)
前后端联调时,一直报500,应该就是后端的跨域配置有问题, 前端配置了 myAxios.defaults.withCredentials = true;
后端使用cors无效
h.Use(cors.New(cors.Config{
AllowAllOrigins: true,
AllowCredentials: true,
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"},
}))

换成gin框架就可以,是我配置的有问题嘛

Proposal: add gRPC example

Is your feature request related to a problem? Please describe.

Although we already have kitex, it cannot be ruled out that many users still use gRPC.

Describe the solution you'd like

add gRPC example.

Additional context

I'd like to try to resolve it if it is ok.

POST单元测试测试咨询

首先,非常感谢开放hertz框架

我在使用代码这段验证的时候,使用下面的代码进行单元测试,发现Name或者name,单测用例校验都会报错

2023/09/26 18:19:03.283748 engine.go:617: [Debug] HERTZ: Method=POST   absolutePath=/v1/user/create           --> handlerName=hertz/demo/biz/handler/user_gorm.CreateUser (num=2 handlers)
{"code":2,"msg":"validating: expr_path=Name, cause=invalid"}--- PASS: TestPerformRequest (0.04s)

下面是单测代码,希望能指出POST方法需要如何正确封装请求🙇‍,避免上面的问题

package user_gorm

import (
	"bytes"
	"fmt"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/test/assert"
	"github.com/cloudwego/hertz/pkg/common/ut"
	"testing"
)

func TestPerformRequest(t *testing.T) {
	h := server.Default()
	h.POST("/v1/user/create", CreateUser)
	json := `{Name:"gdx", "gender": 1, "age": 10, "introduce": "?"}`
	w := ut.PerformRequest(h.Engine, "POST", "/v1/user/create",
		&ut.Body{Body: bytes.NewBufferString(json), Len: len(json)},
		ut.Header{"Connection", "close"})
	resp := w.Result()
	assert.DeepEqual(t, 200, resp.StatusCode())
	// 打印响应体
	fmt.Printf(string(resp.Body()))
}

ktls feature

ktls have 30% speed improvement. possible to implement this?

跨域demo没有生效

Describe the bug

运行 middleware/CORS 下代码,返回的请求头还是没有带跨域的,option请求也会返回404

Hertz version:

v0.1.0

Environment:
GOVERSION="go1.18.3"

Additional context

h.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},              // Allowed domains, need to bring schema
		AllowMethods:     []string{"*"},              // Allowed request methods
		AllowHeaders:     []string{"*"},              // Allowed request headers
		ExposeHeaders:    []string{"Content-Length"}, // Request headers allowed in the upload_file
		AllowCredentials: true,                       // Whether cookies are attached
		MaxAge:           12 * time.Hour,             // Maximum length of upload_file-side cache preflash requests (seconds)
	}))

[DOC] The link of forward proxy should be updated!

Describe the bug

The link of forward proxy is 404 now.

To Reproduce

Steps to reproduce the behavior:

  1. Go to 'client/forward_proxy/README.md'
  2. Click on the link of forward proxy
  3. See 404 error
  4. However if search in doc the content shows in here

Expected behavior

The link of forward proxy should be updated.

Screenshots

The link in readme shows 404 error:

image

and I guess the link changes to

image

and the link is changed in doc

image

Hertz version:

hz version v0.6.4

Environment:

Just a doc issue, I believe you don't need the output of go env.

关于tiktok_demo中,用户服务注册登陆接口handler逻辑问题

Describe the bug
tiktok_demo中,用户服务注册登陆接口handler逻辑问题
To Reproduce

  1. 代码位置在:
    bizdemo/tiktok_demo/biz/handler/user/user_handler.go:59 —— 84
  2. 在insert过后,应该是直接返回resp吧
    下面的
jwt.JwtMiddleware.LoginHandler(ctx, c)
	token := c.GetString("token")
	v, _ := c.Get("user_id")
	user_id := v.(int64)
	c.JSON(consts.StatusOK, user.DouyinUserRegisterResponse{
		StatusCode: errno.SuccessCode,
		StatusMsg:  errno.SuccessMsg,
		Token:      token,
		UserId:     user_id,
	})

应该是放在login的handler逻辑里面,来执行jwt的拦截

// UserLogin .
// @router /user/login/ [POST]
func UserLogin(ctx context.Context, c *app.RequestContext) {
	jwt.JwtMiddleware.LoginHandler(ctx, c)
	token := c.GetString("token")
	v, _ := c.Get("user_id")
	user_id := v.(int64)
	c.JSON(consts.StatusOK, user.UserRegisterResponse{
		StatusCode: errno.SuccessCode,
		StatusMsg:  errno.SuccessMsg,
		Token:      token,
		UserId:     user_id,
	})
}

how to get multi values from select html multiple?

my form has <select name="g" multiple><option name="70010000">70010000</option> ... etc.

i got only the first value using the below form using


                g := c.PostForm("g")
                fmt.Printf("g = %s\n",g)
                //g = 70010000

but how do i get all the values below?

    g:[70010000 70010700 70010300]


` {{} [] } %!s(bool=false) %!s(bool=false)    } {{} [] } <nil> {%!s(*protocol.Request=<nil>)} %!s(*bytebufferpool.ByteBuffer=<nil>)  %!s(int=4194304) %!s(*multipart.Form=&{map[city:[] country:[] d:[] f[]:[                       ] g:[70010000 70010700 70010300] h:[] n:[] state:[] v:[  ]] map[]}) ----WebKitFormBoundarypcGsJBqbVr5PnXRl %!s(bool=true) %!s(bool=true) %!s(bool=false) [] [] %!s(*config.RequestOptions=<nil>)} {{} {{} %!s(bool=false) %!s(bool=false) %!s(bool=false) %!s(bool=false) %!s(bool=false) %!s(int=0) %!s(int=0)   hertz [] { HTTP/1.1 200 OK

Feature request: Using hertz to complete a github data analysis project

Is your feature request related to a problem? Please describe.

  • We need a github data analytics project to help us present the community's data,the need for customisation is greater, to the extent that we can't use open source existing products

Describe the solution you'd like

  • using hertz to complete a github data analysis project and add it to hertz-examples or biz-examples

Describe alternatives you've considered

  • None

Additional context

  • None

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.