http.go 1.12 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
package server

import (
	"github.com/go-kratos/kratos/v2/middleware/auth/jwt"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/http"
	jwtv4 "github.com/golang-jwt/jwt/v4"
	"gokratos-base/api/service/demo"
	"gokratos-base/app/service/demo/internal/conf"
	"gokratos-base/app/service/demo/internal/service"
	"gokratos-base/common/httpext"
	"time"
)

// NewHTTPServer new a http server.
func NewHTTPServer(c *conf.Server, svc *service.DemoService) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			tracing.Server(),
			jwt.Server(func(token *jwtv4.Token) (interface{}, error) {
				return []byte("testkey"), nil
			}),
			ValidateParams(),
		),
		http.ResponseEncoder(httpext.Encoder),
		http.ErrorEncoder(httpext.ErrorEncoder),
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != 0 {
		opts = append(opts, http.Timeout(time.Duration(c.Grpc.Timeout)*time.Second))
	}
	srv := http.NewServer(opts...)
	demo.RegisterDemoHTTPServer(srv, svc)
	return srv
}