Coder Social home page Coder Social logo

Comments (4)

dosubot avatar dosubot commented on July 18, 2024 2

🤖

It's great that you've identified a potential improvement in the http.wrapper.Result() method. Your understanding of the code and the proposed change seem well-reasoned. If you believe this change would benefit the project, I encourage you to create a pull request with your proposed modification. Your contribution could help improve the project for everyone. Thank you for considering to contribute!


This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.

Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.

If you want to continue the conversation, start your reply with @dosu-bot.

from kratos.

kvii avatar kvii commented on July 18, 2024

我看完源码后猜测可能是因为这个原因:

  1. 仔细看 responseWriter 类型的方法,它实现了一个类似于“缓存响应码”的功能。

    func (w *responseWriter) WriteHeader(statusCode int) { w.code = statusCode }
    func (w *responseWriter) Write(data []byte) (int, error) {
    w.w.WriteHeader(w.code)
    return w.w.Write(data)
    }

  2. 这是 Result 方法,可以看到和其他方法相比,如 "JSON",它缺少了设置 "Content-Type" 响应头的步骤,直接设置了响应码。

    func (c *wrapper) Result(code int, v interface{}) error {
    c.w.WriteHeader(code)
    return c.router.srv.enc(&c.w, c.req, v)
    }
    func (c *wrapper) JSON(code int, v interface{}) error {
    c.res.Header().Set("Content-Type", "application/json")
    c.res.WriteHeader(code)
    return json.NewEncoder(c.res).Encode(v)
    }

  3. 在默认的 enc 函数中操作了 header,根据数据类型添加了对应响应头。

    w.Header().Set("Content-Type", httputil.ContentType(codec.Name()))

  4. go 源码中 ResponseWriter 的 Header 的注释中说了,设置了响应码之后,Header 的更改就无效了。
    https://github.com/golang/go/blob/f719d5cffdb8298eff7a5ef533fe95290e8c869c/src/net/http/server.go#L99-L101

所以我推测,是因为必须在 Result 等方法中先设置响应码。而先设置响应码会导致响应头的修改无效。所以才有了 responseWriter。不过不论如何,这里肯定有问题就是了,起码 c.res 和 c.w 不应该同时存在。

from kratos.

kratos-ci-bot avatar kratos-ci-bot commented on July 18, 2024

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


After reading the source code, I guessed it might be because of this:

  1. Look carefully at the method of the responseWriter type. It implements a function similar to "caching response codes".

    func (w *responseWriter) WriteHeader(statusCode int) { w.code = statusCode }
    func (w *responseWriter) Write(data []byte) (int, error) {
    w.w.WriteHeader(w.code)
    return w.w.Write(data)
    }

  2. This is the Result method. You can see that compared with other methods, such as "JSON", it lacks the step of setting the "Content-Type" response header and directly sets the response code.

    func (c *wrapper) Result(code int, v interface{}) error {
    c.w.WriteHeader(code)
    return c.router.srv.enc(&c.w, c.req, v)
    }

  3. The header is operated in the default enc function and the corresponding response header is added according to the data type.

    w.Header().Set("Content-Type", httputil.ContentType(codec.Name()))

  4. The comments on the Header of ResponseWriter in the go source code say that after the response code is set, changes to the Header will be invalid.
    https://github.com/golang/go/blob/f719d5cffdb8298eff7a5ef533fe95290e8c869c/src/net/http/server.go#L99-L101

So I speculate that it is because the response code must be set first in methods such as Result. Setting the response code first will cause the modification of the response header to be invalid. That's why there is responseWriter. But no matter what, there must be a problem here. At least c.res and c.w should not exist at the same time.

from kratos.

kvii avatar kvii commented on July 18, 2024

@xbchaos Use can use the code below when kratos version >= v2.7.3 to get the underlying custom writer that you've set before:
If you think this code can solve your problem, remember to close this issue.
PR reference: #3265

package main

import (
	"context"
	"fmt"
	"io"
	nt "net/http"
	"net/http/httptest"

	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport/http"
)

type customWriter struct {
	http.ResponseWriter
}

func main() {
	s := http.NewServer(
		http.Middleware(func(h middleware.Handler) middleware.Handler {
			return func(ctx context.Context, req any) (any, error) {
				hc := ctx.(http.Context)
				hc.Reset(customWriter{hc.Response()}, hc.Request()) // reset response writer
				return h(ctx, req)
			}
		}),
		http.ResponseEncoder(func(w http.ResponseWriter, r *http.Request, v any) error {
			// get underlying response writer
			var ok bool
			under := w
		out:
			for {
				switch cur := under.(type) {
				case customWriter:
					under = cur
					ok = true
					break out
				case interface{ Unwrap() http.ResponseWriter }:
					under = cur.Unwrap()
				default:
					break out
				}
			}
			return http.DefaultResponseEncoder(w, r, ok)
		}),
	)

	// simulate what happened in xx_http.pb.go
	s.Route("/").GET("/a", func(ctx http.Context) error {
		h := ctx.Middleware(func(ctx context.Context, req any) (any, error) {
			return nil, nil
		})
		out, _ := h(ctx, nil)
		return ctx.Result(200, out)
	})

	w := httptest.NewRecorder()
	r := httptest.NewRequest(nt.MethodGet, "/a", nil)
	s.ServeHTTP(w, r)
	res := w.Result()
	defer res.Body.Close()

	bs, _ := io.ReadAll(res.Body)
	fmt.Println(string(bs)) // true
}

from kratos.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.