HTTP

    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:

    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. data, err := codec.Marshal(v)
    5. if err != nil {
    6. return err
    7. }
    8. // Write the scheme of the encoder in the Response Header
    9. w.Header().Set("Content-Type", httputil.ContentType(codec.Name()))
    10. return nil
    11. }

    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. }

    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

    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. }

    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

    Client

    WithTransport(trans http.RoundTripper) ClientOption

    Configure the client’s HTTP RoundTripper

    WithTimeout(d time.Duration) ClientOption

    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

    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. // Obtain the encoder type through the externally configured contentType
    2. name := httputil.ContentSubtype(contentType)
    3. // Get the actual encoder
    4. body, err := encoding.GetCodec(name).Marshal(in)
    5. if err != nil {
    6. return nil, err
    7. }
    8. return body, err
    9. }

    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:

    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

    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. )

    Use service discovery