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:
func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error {
// Extract the corresponding encoder from the Accept of Request Header
// If not found, ignore the error and use the default json encoder
data, err := codec.Marshal(v)
if err != nil {
return err
}
// Write the scheme of the encoder in the Response Header
w.Header().Set("Content-Type", httputil.ContentType(codec.Name()))
return nil
}
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:
func DefaultErrorEncoder(w http.ResponseWriter, r *http.Request, err error) {
// Get error and convert it into kratos Error entity
se := errors.FromError(err)
// Extract the corresponding encoder from the Accept of Request Header
codec, _ := CodecForRequest(r, "Accept")
body, err := codec.Marshal(se)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", httputil.ContentType(codec.Name()))
// Set HTTP Status Code
w.WriteHeader(int(se.Code))
w.Write(body)
}
NewServer(opts ...ServerOption) *Server
Pass in opts configuration and start HTTP Server
hs := http.NewServer()
app := kratos.New(
kratos.Name("kratos"),
kratos.Version("v1.0.0"),
kratos.Server(hs),
)
Use kratos middleware in HTTP server
Handling http requests in middleware
if tr, ok := transport.FromServerContext(ctx); ok {
kind = tr.Kind().String()
operation = tr.Operation()
// Assert that HTTP transport can get special information
if ht,ok := tr.(*http.Tranport);ok{
fmt.Println(ht.Request())
}
}
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:
r := s.Route("/v1")
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:
// Obtain the encoder type through the externally configured contentType
name := httputil.ContentSubtype(contentType)
// Get the actual encoder
body, err := encoding.GetCodec(name).Marshal(in)
if err != nil {
return nil, err
}
return body, err
}
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:
func DefaultErrorDecoder(ctx context.Context, res *http.Response) error {
// HTTP Status Code is the highest priority
if res.StatusCode >= 200 && res.StatusCode <= 299 {
return nil
}
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err == nil {
e := new(errors.Error)
// Here you get the corresponding response decoder according to the Content-Type in the Response Header
// Then parse out the main content of the error
if err = CodecForResponse(res).Unmarshal(data, e); err == nil {
// HTTP Status Code is the highest priority
e.Code = int32(res.StatusCode)
return e
}
}
// If no valid Response Body is returned, the HTTP Status Code shall prevail
return errors.Errorf(res.StatusCode, errors.UnknownReason, err.Error())
}
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
conn, err := http.NewClient(
context.Background(),
http.WithEndpoint("127.0.0.1:8000"),
)
Use middleware
conn, err := http.NewClient(
context.Background(),
http.WithEndpoint("127.0.0.1:9000"),
http.WithMiddleware(
recovery.Recovery(),
)