Repository: cloudwego/hertz (go)

Issue:
error 	addr := conn.LocalAddr().String() //:796
with this error. 
go get github.com/cloudwego/hertz@develop

```
server.WithOnAccept(func(conn network.Conn) context.Context {
	addr := conn.LocalAddr().String() //:796
	log.Printf("BADIP CHECK = %s\n", addr)
	//if isBadIp(addr) {
	//	conn.Close()
	//}
	return context.Background()
}),
```				
https://github.com/cloudwego/hertz/issues/479
```
2023/01/03 19:34:32.569672 engine.go:389: [Info] HERTZ: Using network library=standard
2023/01/03 19:34:32.570042 transport.go:65: [Info] HERTZ: HERTZ: HTTP server listening on address=[::]:443
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x30 pc=0xf6a7de]

goroutine 10 [running]:
main.main.func6({0x0?, 0x0?})
        /go/src/example.com/cloud/app/frwll/http2/frwll10.go:796 +0x1e
github.com/cloudwego/hertz/pkg/network/standard.(*transport).serve(0xc000185a00)
        /root/go/pkg/mod/github.com/cloudwego/hertz@v0.4.3-0.20230103082611-81332e6a707d/pkg/network/standard/transport.go:76 +0x2cf
github.com/cloudwego/hertz/pkg/network/standard.(*transport).ListenAndServe(0x1c29f40?, 0x120693e?)
        /root/go/pkg/mod/github.com/cloudwego/hertz@v0.4.3-0.20230103082611-81332e6a707d/pkg/network/standard/transport.go:94 +0x33
github.com/cloudwego/hertz/pkg/route.(*Engine).listenAndServe(0xc0001518c0)
        /root/go/pkg/mod/github.com/cloudwego/hertz@v0.4.3-0.20230103082611-81332e6a707d/pkg/route/engine.go:390 +0x122
github.com/cloudwego/hertz/pkg/route.(*Engine).Run(0xc0001518c0)
        /root/go/pkg/mod/github.com/cloudwego/hertz@v0.4.3-0.20230103082611-81332e6a707d/pkg/route/engine.go:357 +0x16a
github.com/cloudwego/hertz/pkg/app/server.(*Hertz).Spin.func1()
        /root/go/pkg/mod/github.com/cloudwego/hertz@v0.4.3-0.20230103082611-81332e6a707d/pkg/app/server/hertz.go:61 +0x29
created by github.com/cloudwego/hertz/pkg/app/server.(*Hertz).Spin
        /root/go/pkg/mod/github.com/cloudwego/hertz@v0.4.3-0.20230103082611-81332e6a707d/pkg/app/server/hertz.go:60 +0xca
child 1 exited with error: exit status 2
```

Pull request:
fix: OnAccept panic
#### What type of PR is this?
<!--
Add one of the following kinds:

build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
docs: Documentation only changes
feat: A new feature
optimize: A new optimization
fix: A bug fix
perf: A code change that improves performance
refactor: A code change that neither fixes a bug nor adds a feature
style: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc)
test: Adding missing tests or correcting existing tests
chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
-->
fix
#### Check the PR title.
<!--
The description of the title will be attached in Release Notes, 
so please describe it from user-oriented, what this PR does / why we need it.
Please check your PR title with the below requirements:
-->
- [ ] This PR title match the format: \<type\>(optional scope): \<description\>
- [ ] The description of this PR title is user-oriented and clear enough for others to understand.


#### (Optional) Translate the PR title into Chinese.
OnAccept 方法在标准库下会 panic

#### (Optional) More detail description for this PR(en: English/zh: Chinese).
<!--
Provide more detailed info for review. If it is a perf type PR, perf data is suggested to give.
-->
en: OnAccept panic when use standard library
zh(optional): OnAccept 方法在标准库下会 panic

#### Which issue(s) this PR fixes:
<!--
Automatically closes linked issue when PR is merged.
Eg: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->
close #507 

Patch:
diff --git a/cmd/hz/app/app.go b/cmd/hz/app/app.go
index 4261bd4..a66f624 100644
--- a/cmd/hz/app/app.go
+++ b/cmd/hz/app/app.go
@@ -141,7 +141,7 @@ func Init() *cli.App {
 	outDirFlag := cli.StringFlag{Name: "out_dir", Usage: "Specify the project path.", Destination: &globalArgs.OutDir}
 	handlerDirFlag := cli.StringFlag{Name: "handler_dir", Usage: "Specify the handler path.", Destination: &globalArgs.HandlerDir}
 	modelDirFlag := cli.StringFlag{Name: "model_dir", Usage: "Specify the model path.", Destination: &globalArgs.ModelDir}
-	clientDirFlag := cli.StringFlag{Name: "client_dir", Usage: "Specify the client path. If not specified, no client code is generated.", Destination: &globalArgs.ClientDir}
+	clientDirFlag := cli.StringFlag{Name: "client_dir", Usage: "Specify the client path. If not specified, IDL generated path is used for 'client' command; no client code is generated for 'new' command", Destination: &globalArgs.ClientDir}
 
 	optPkgFlag := cli.StringSliceFlag{Name: "option_package", Aliases: []string{"P"}, Usage: "Specify the package path. ({include_path}={import_path})"}
 	includesFlag := cli.StringSliceFlag{Name: "proto_path", Aliases: []string{"I"}, Usage: "Add an IDL search path for includes. (Valid only if idl is protobuf)"}
@@ -263,6 +263,7 @@ func Init() *cli.App {
 				&idlFlag,
 				&moduleFlag,
 				&modelDirFlag,
+				&clientDirFlag,
 
 				&includesFlag,
 				&thriftOptionsFlag,
diff --git a/cmd/hz/generator/client.go b/cmd/hz/generator/client.go
index 7ad2b1c..37b2cac 100644
--- a/cmd/hz/generator/client.go
+++ b/cmd/hz/generator/client.go
@@ -44,7 +44,7 @@ type ClientFile struct {
 func (pkgGen *HttpPackageGenerator) genClient(pkg *HttpPackage, clientDir string) error {
 	for _, s := range pkg.Services {
 		cliDir := util.SubDir(clientDir, util.ToSnakeCase(s.Name))
-		hertzClientPath := filepath.Join(cliDir, "hertz_client.go")
+		hertzClientPath := filepath.Join(cliDir, hertzClientTplName)
 		isExist, err := util.PathExist(hertzClientPath)
 		if err != nil {
 			return err
diff --git a/cmd/hz/generator/package.go b/cmd/hz/generator/package.go
index fa8a6a5..0476271 100644
--- a/cmd/hz/generator/package.go
+++ b/cmd/hz/generator/package.go
@@ -141,9 +141,12 @@ func (pkgGen *HttpPackageGenerator) Generate(pkg *HttpPackage) error {
 	}
 
 	if pkgGen.CmdType == meta.CmdClient {
+		// default client dir
 		clientDir := pkgGen.IdlClientDir
-		// support multiple service, so disable "clientDir/hertz"
-		// clientDir = util.SubDir(clientDir, "hertz")
+		// user specify client dir
+		if len(pkgGen.ClientDir) != 0 {
+			clientDir = pkgGen.ClientDir
+		}
 		if err := pkgGen.genClient(pkg, clientDir); err != nil {
 			return err
 		}
diff --git a/cmd/hz/generator/package_tpl.go b/cmd/hz/generator/package_tpl.go
index ac2197b..3eba61e 100644
--- a/cmd/hz/generator/package_tpl.go
+++ b/cmd/hz/generator/package_tpl.go
@@ -289,9 +289,12 @@ type use interface {
 
 // Definition of global data and types.
 type ResponseResultDecider func(statusCode int, rawResponse *protocol.Response) (isError bool)
-type bindRequestBodyFunc func(c *cli, r *request) (contentType string, body io.Reader, err error)
-type beforeRequestFunc func(*cli, *request) error
-type afterResponseFunc func(*cli, *response) error
+
+type (
+	bindRequestBodyFunc func(c *cli, r *request) (contentType string, body io.Reader, err error)
+	beforeRequestFunc   func(*cli, *request) error
+	afterResponseFunc   func(*cli, *response) error
+)
 
 var (
 	hdrContentTypeKey     = http.CanonicalHeaderKey("Content-Type")
@@ -906,11 +909,13 @@ func (s *{{$.ServiceName}}Client) {{$MethodInfo.Name}}(context context.Context,
 		setRequestOption(reqOpt...).
 		setResult(httpResp).
 		execute("{{$MethodInfo.HTTPMethod}}", "{{$MethodInfo.Path}}")
-	if err == nil {
-		resp = httpResp
+	if err != nil {
+		return nil, nil, err
 	}
+    
+	resp = httpResp
 	rawResponse = ret.rawResponse
-	return resp, rawResponse, err
+	return resp, rawResponse, nil
 }
 {{end}}
 
diff --git a/pkg/app/server/option.go b/pkg/app/server/option.go
index 7395775..bf44829 100644
--- a/pkg/app/server/option.go
+++ b/pkg/app/server/option.go
@@ -333,7 +333,7 @@ func WithDisablePrintRoute(b bool) config.Option {
 
 // WithOnAccept sets the callback function when a new connection is accepted but cannot
 // receive data in netpoll. In go net, it will be called before converting tls connection
-func WithOnAccept(fn func(conn network.Conn) context.Context) config.Option {
+func WithOnAccept(fn func(conn net.Conn) context.Context) config.Option {
 	return config.Option{F: func(o *config.Options) {
 		o.OnAccept = fn
 	}}
diff --git a/pkg/common/config/option.go b/pkg/common/config/option.go
index 3ba3d38..03c84a0 100644
--- a/pkg/common/config/option.go
+++ b/pkg/common/config/option.go
@@ -83,7 +83,7 @@ type Options struct {
 	// If you'd like to check whether the peer IP is in the blacklist, you can use OnAccept.
 	// In go net, OnAccept is executed after connection accepted but before establishing
 	// tls connection. OnConnect is executed after establishing tls connection.
-	OnAccept  func(conn network.Conn) context.Context
+	OnAccept  func(conn net.Conn) context.Context
 	OnConnect func(ctx context.Context, conn network.Conn) context.Context
 
 	// Registry is used for service registry.
diff --git a/pkg/network/netpoll/transport.go b/pkg/network/netpoll/transport.go
index da28bf2..c213060 100644
--- a/pkg/network/netpoll/transport.go
+++ b/pkg/network/netpoll/transport.go
@@ -41,7 +41,7 @@ type transporter struct {
 	listener         net.Listener
 	eventLoop        netpoll.EventLoop
 	listenConfig     *net.ListenConfig
-	OnAccept         func(conn network.Conn) context.Context
+	OnAccept         func(conn net.Conn) context.Context
 	OnConnect        func(ctx context.Context, conn network.Conn) context.Context
 }
 
diff --git a/pkg/network/standard/transport.go b/pkg/network/standard/transport.go
index b6131b2..2605b2e 100644
--- a/pkg/network/standard/transport.go
+++ b/pkg/network/standard/transport.go
@@ -46,7 +46,7 @@ type transport struct {
 	tls              *tls.Config
 	listenConfig     *net.ListenConfig
 	lock             sync.Mutex
-	OnAccept         func(conn network.Conn) context.Context
+	OnAccept         func(conn net.Conn) context.Context
 	OnConnect        func(ctx context.Context, conn network.Conn) context.Context
 }
 
@@ -73,7 +73,7 @@ func (t *transport) serve() (err error) {
 		}
 
 		if t.OnAccept != nil {
-			ctx = t.OnAccept(c)
+			ctx = t.OnAccept(conn)
 		}
 
 		if t.tls != nil {


Test patch:
diff --git a/pkg/app/server/hertz_test.go b/pkg/app/server/hertz_test.go
index c5c1c8e..de6a593 100644
--- a/pkg/app/server/hertz_test.go
+++ b/pkg/app/server/hertz_test.go
@@ -803,7 +803,7 @@ func TestOnprepare(t *testing.T) {
 	assert.DeepEqual(t, "the server closed connection before returning the first response byte. Make sure the server returns 'Connection: close' response header before closing the connection", err.Error())
 
 	h = New(
-		WithOnAccept(func(conn network.Conn) context.Context {
+		WithOnAccept(func(conn net.Conn) context.Context {
 			conn.Close()
 			return context.Background()
 		}),
@@ -817,4 +817,18 @@ func TestOnprepare(t *testing.T) {
 	if err == nil {
 		t.Fatalf("err should not be nil")
 	}
+
+	h = New(
+		WithOnAccept(func(conn net.Conn) context.Context {
+			assert.DeepEqual(t, conn.LocalAddr().String(), "127.0.0.1:9231")
+			return context.Background()
+		}),
+		WithHostPorts("localhost:9231"),
+		WithTransport(standard.NewTransporter))
+	h.GET("/ping", func(ctx context.Context, c *app.RequestContext) {
+		c.JSON(consts.StatusOK, utils.H{"ping": "pong"})
+	})
+	go h.Spin()
+	time.Sleep(time.Second)
+	c.Get(context.Background(), nil, "http://127.0.0.1:9231/ping")
 }