HTTP

Transporter/http is based on the gorilla/mux HTTP routing framework to implement Transporter to register http to kratos.Server().

Server

Configuration

Network(network string) ServerOption

Configure the network protocol of the server, such as tcp

Address(addr string) ServerOption

Configure the server listening address

Timeout(timeout time.Duration) ServerOption

Configure server timeout settings

Logger(logger log.Logger) ServerOption

Configure log which used in http server

Middleware(m ...middleware.Middleware) ServerOption

Configure the kratos service middleware on the server side

Filter(filters ...FilterFunc) ServerOption

Configure the server-side kratos global HTTP native Fitler, the execution order of this Filter is before the Service middleware

RequestDecoder(dec DecodeRequestFunc) ServerOption

Configure the HTTP Request Decode method of the Kratos server to parse the Request Body into a user-defined pb structure Let’s see how the default RequestDecoder in kratos is implemented:

  1. func DefaultRequestDecoder(r *http.Request, v interface{}) error {
  2. // Extract the corresponding decoder from the Content-Type of the Request Header
  3. codec, ok := CodecForRequest(r, "Content-Type")
  4. // If the corresponding decoder cannot be found, an error will be reported at this time
  5. if !ok {
  6. return errors.BadRequest("CODEC", r.Header.Get("Content-Type"))
  7. }
  8. data, err := ioutil.ReadAll(r.Body)
  9. if err != nil {
  10. return errors.BadRequest("CODEC", err.Error())
  11. }
  12. if err = codec.Unmarshal(data, v); err != nil {
  13. return errors.BadRequest("CODEC", err.Error())
  14. }
  15. return nil
  16. }

Then if we want to extend or replace the parsing implementation corresponding to Content-Type, we can use http.RequestDecoder() to replace Kratos’s default RequestDecoder, Or it can be extended by registering or overwriting a codec corresponding to a Content-Type in encoding

ResponseEncoder(en EncodeResponseFunc) ServerOption

Configure the HTTP Response Encode method of the Kratos server to serialize the reply structure in the user pb definition and write it into the Response Body Let’s see how the default ResponseEncoder in kratos is implemented:

  1. func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error {
  2. // Extract the corresponding encoder from the Accept of Request Header
  3. // If not found, ignore the error and use the default json encoder
  4. codec, _ := CodecForRequest(r, "Accept")
  5. data, err := codec.Marshal(v)
  6. if err != nil {
  7. return err
  8. }
  9. // Write the scheme of the encoder in the Response Header
  10. w.Header().Set("Content-Type", httputil.ContentType(codec.Name()))
  11. w.Write(data)
  12. return nil
  13. }

Then if we want to extend or replace the serialization implementation corresponding to Accept, we can use http.ResponseEncoder() to replace the default ResponseEncoder of Kratos, Or it can be extended by registering or overwriting a codec corresponding to Accept in encoding

ErrorEncoder(en EncodeErrorFunc) ServerOption

Configure the HTTP Error Encode method of the Kratos server to serialize the error thrown by the business and write it into the Response Body, and set the HTTP Status Code Let’s see how the default ErrorEncoder in kratos is implemented:

  1. func DefaultErrorEncoder(w http.ResponseWriter, r *http.Request, err error) {
  2. // Get error and convert it into kratos Error entity
  3. se := errors.FromError(err)
  4. // Extract the corresponding encoder from the Accept of Request Header
  5. codec, _ := CodecForRequest(r, "Accept")
  6. body, err := codec.Marshal(se)
  7. if err != nil {
  8. w.WriteHeader(http.StatusInternalServerError)
  9. return
  10. }
  11. w.Header().Set("Content-Type", httputil.ContentType(codec.Name()))
  12. // Set HTTP Status Code
  13. w.WriteHeader(int(se.Code))
  14. w.Write(body)
  15. }

Start Server

NewServer(opts ...ServerOption) *Server

Pass in opts configuration and start HTTP Server

  1. hs := http.NewServer()
  2. app := kratos.New(
  3. kratos.Name("kratos"),
  4. kratos.Version("v1.0.0"),
  5. kratos.Server(hs),
  6. )

Use kratos middleware in HTTP server

  1. hs := http.NewServer(
  2. http.Address(":8000"),
  3. http.Middleware(
  4. logging.Server(),
  5. ),
  6. )

Handling http requests in middleware

  1. if tr, ok := transport.FromServerContext(ctx); ok {
  2. kind = tr.Kind().String()
  3. operation = tr.Operation()
  4. // Assert that HTTP transport can get special information
  5. if ht,ok := tr.(*http.Tranport);ok{
  6. fmt.Println(ht.Request())
  7. }
  8. }

Server Router

func (s *Server) Route(prefix string, filters ...FilterFunc) *Router

Create a new HTTP Server Router, which can pass Kraots’ HTTP Filter interceptor at the same time Let’s look at the usage:

  1. r := s.Route("/v1")
  2. r.GET("/helloworld/{name}", _Greeter_SayHello0_HTTP_Handler(srv))

func (s *Server) Handle(path string, h http.Handler)

Add the path to the route and use the standard HTTP Handler to handle it

func (s *Server) HandlePrefix(prefix string, h http.Handler)

The prefix matching method adds the prefix to the route and uses the standard HTTP Handler to handle it

func (s *Server) ServeHTTP(res http.ResponseWriter, req *http.Request)

Implemented the HTTP Handler interface of the standard library

Reference for other routing usage methods: https://github.com/go-kratos/examples/tree/main/http/middlewares

Use gin framework in Kratos HTTP: https://github.com/go-kratos/kratos/blob/main/examples/http/gin/main.go

Client

Configuration

WithTransport(trans http.RoundTripper) ClientOption

Configure the client’s HTTP RoundTripper

WithTimeout(d time.Duration) ClientOption

Configure the default timeout time of the client request, if there is a link timeout, the link timeout time is preferred

WithUserAgent(ua string) ClientOption

Configure the default User-Agent of the client

WithMiddleware(m ...middleware.Middleware) ClientOption

Configure the kratos client middleware used by the client

WithEndpoint(endpoint string) ClientOption

Configure the peer connection address used by the client, if you do not use service discovery, it is ip:port, if you use service discovery, the format is discovery://\<authority>/\<serviceName>, here\<authority> You can fill in the blanks by default

WithDiscovery(d registry.Discovery) ClientOption

Configure service discovery used by the client

WithRequestEncoder(encoder EncodeRequestFunc) ClientOption

Configure the HTTP Request Encode method of the client to serialize the user-defined pb structure to the Request Body Let’s look at the default encoder:

  1. func DefaultRequestEncoder(ctx context.Context, contentType string, in interface{}) ([]byte, error) {
  2. // Obtain the encoder type through the externally configured contentType
  3. name := httputil.ContentSubtype(contentType)
  4. // Get the actual encoder
  5. body, err := encoding.GetCodec(name).Marshal(in)
  6. if err != nil {
  7. return nil, err
  8. }
  9. return body, err
  10. }

WithResponseDecoder(decoder DecodeResponseFunc) ClientOption

Configure the HTTP Response Decode method of the client to parse the Response Body into a user-defined pb structure Let’s see how the default decoder in kratos is implemented:

  1. func DefaultResponseDecoder(ctx context.Context, res *http.Response, v interface{}) error {
  2. defer res.Body.Close()
  3. data, err := ioutil.ReadAll(res.Body)
  4. if err != nil {
  5. return err
  6. }
  7. // Here you get the corresponding decoder according to the Content-Type in the Response Header
  8. // Then proceed to Unmarshal
  9. return CodecForResponse(res).Unmarshal(data, v)
  10. }

WithErrorDecoder(errorDecoder DecodeErrorFunc) ClientOption

Configure the client’s Error parsing method Let’s take a look at how the default error decoder in kratos is implemented:

  1. func DefaultErrorDecoder(ctx context.Context, res *http.Response) error {
  2. // HTTP Status Code is the highest priority
  3. if res.StatusCode >= 200 && res.StatusCode <= 299 {
  4. return nil
  5. }
  6. defer res.Body.Close()
  7. data, err := ioutil.ReadAll(res.Body)
  8. if err == nil {
  9. e := new(errors.Error)
  10. // Here you get the corresponding response decoder according to the Content-Type in the Response Header
  11. // Then parse out the main content of the error
  12. if err = CodecForResponse(res).Unmarshal(data, e); err == nil {
  13. // HTTP Status Code is the highest priority
  14. e.Code = int32(res.StatusCode)
  15. return e
  16. }
  17. }
  18. // If no valid Response Body is returned, the HTTP Status Code shall prevail
  19. return errors.Errorf(res.StatusCode, errors.UnknownReason, err.Error())
  20. }

WithBalancer(b balancer.Balancer) ClientOption

Configure the client’s load balancing strategy

WithBlock() ClientOption

Configure the dial policy of the client to be blocking (it will not return until the service discovers the node), and the default is asynchronous and non-blocking

Client usage

Create a client connection

  1. conn, err := http.NewClient(
  2. context.Background(),
  3. http.WithEndpoint("127.0.0.1:8000"),
  4. )

Use middleware

  1. conn, err := http.NewClient(
  2. context.Background(),
  3. http.WithEndpoint("127.0.0.1:9000"),
  4. http.WithMiddleware(
  5. recovery.Recovery(),
  6. ),
  7. )

Use service discovery

  1. conn, err := http.NewClient(
  2. context.Background(),
  3. http.WithEndpoint("discovery:///helloworld"),
  4. http.WithDiscovery(r),
  5. )