0

I am using go-swagger but I have an case where I want to write a string to a response. I need to call the "WriteResponse" function

WriteResponse(rw http.ResponseWriter, producer runtime.Producer)

The issue that I am having is that I don't know how to convert a string to a http.ResponseWriter and create a runtime.Producer.

If it helps here is a snippit of my code...

//convert the database response to a string array of valid JSON
stringArray, conversionError := plan.ConvertPlanArrayToString(response)
if conversionError != nil {
    return swaggerPlan.NewPlanGetTemplatePlanInternalServerError()
}

//Need to convert string value
stringValue := stringArray[0]
return swaggerPlan.NewPlanGetTemplatePlanOK().WriteResponse(NOT SURE HOW TO CREATE http.ResponseWriter, runtime.Producer)

Thank you very much

mornindew
  • 1,993
  • 6
  • 32
  • 54
  • You don't convert a string to a ResponseWriter. But you can _write_ a string to a ResponseWriter. As for your runtime.Producer type--what is that? It's not part of the standard library runtime package. – Jonathan Hall Sep 20 '18 at 07:23

2 Answers2

0

As mentioned by Flimzy, you'll have to write your string to the http.ResponseWriter, which is probably what your WriteResponse function does anyway.

The code you provided should somewhere be called from within a handler function:

func (...) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  // your code should be here and you can pass the http.ResponseWriter
}
Kevin Sandow
  • 4,003
  • 1
  • 20
  • 33
0

Thank you both very much, you were very helpful. It worked exactly like you said but in go-swagger it is slightly different.

My handler was updated to return a custom "ResponderFunc" and then I could write my output directly to it. Worked great, here is my code...

//Handle a 200 by sending the list of plans back as json
    return middleware.ResponderFunc(func(rw http.ResponseWriter, pr runtime.Producer) {
        rw.WriteHeader(200)
        rw.Write(byteArrayPlan)
    })
mornindew
  • 1,993
  • 6
  • 32
  • 54