无法在GO中将ResponseErrorWriter文字(类型ResponseErrorWriter)用作类型错误

In my GO project I am getting an error in server.go file as,

mygo/testkit/pkg/http/server pkg\http\server\server.go:24: cannot use ResponseErrorWriter literal (type ResponseErrorWriter) as type

tigertonic.ErrorWriter in assignment: ResponseErrorWriter does not implement tigertonic.ErrorWriter (missing WriteError method)

Here is my init() function, which gives the error in server.go.

func init() {
    tt.ResponseErrorWriter = ResponseErrorWriter{}
    tt.SnakeCaseHTTPEquivErrors = false // Ignored in ResponseErrorWriter anyway.
}

And I am getting the error at this line,

tt.ResponseErrorWriter = ResponseErrorWriter{}

What will be the reason for this error? How to solve this? I am new to this GO framework.

From the message, ResponseErrorWriter is not a tigertonic.ErrorWriter. Meaning you haven't created type ResponseErrorWriter struct which implements interface tigertonic.ErrorWriter, so what you are trying to do is to initialize a struct which does not match the expected interface.

The message is clear, you need to implement the WriteError method.

Your issue relies on the following line from original source code :

var ResponseErrorWriter ErrorWriter = defaultErrorWriter{}

type ErrorWriter interface {
    WriteError(r *http.Request, w http.ResponseWriter, err error)
    WriteJSONError(w http.ResponseWriter, err error)
    WritePlaintextError(w http.ResponseWriter, err error)
}

Analyzing the above code it's clear that ResponseErrorWriter is defined as ErrorWriter which means that it's type is a custom type which implements the methods declared inside the interface. This means that you have to implement the methods declared as interface.

An interface defines a set of methods (the method set), but these methods do not contain code: they are not implemented (they are abstract). Interfaces in Go are some kind of contracts between the structs and the methods they needs to implement.


If you really need to implement your ErrorWriter interface, you need to declare your custom struct, which implements the method defined in the original ErrorWriter interface. Then you need to invoke the methods declared. How do you want to handle the errors it all depends on you.

If you check the source you will see that it implemented in the following way:

func (d defaultErrorWriter) WriteError(r *http.Request, w http.ResponseWriter, err error) {
    if acceptJSON(r) {
        d.WriteJSONError(w, err)
    } else {
        d.WritePlaintextError(w, err)
    }
}

The only thing left behind is to define the local struct variable as:

type defaultErrorWriter struct{}