Changing default header for JSON data in Gin - go

I've noticed that using Gin to return a response like this:
c.JSON(http.StatusOK, jsonData)
automatically creates the following header:
application/json; charset=utf-8
Is it possible to modify the header somehow to just return
application/json
I'd rather take this approach than splitting the string at the ;

Modify the source code to remove the ; charset=utf-8 string, or
Have a wrapper function which manually sets Content-Type before the gin.Context.JSON call:
func JSON(c *gin.Context, code int, obj interface{}) {
c.Header("Content-Type", "application/json")
c.JSON(code, obj)
}
// ...
JSON(c, http.StatusOK, jsonData)

You can add new headers in the request like this :
c.Request.Header.Add("x-request-id", requestID)

Related

How to modify headers of WebMVC.fn RouterFunction response?

I've defined a RouterFunction bean, with handler function returning a response with string body, which is a JSON. The builder however sets the content type to text/plain on passing a string to body
ServerResponse.ok().body(responseString).build() // Content type set to text/plain
#Bean
public RouterFunction<ServerResponse> infoRouter(MyHandler myHandler) {
return nest(
path("info"),
route().GET("definitions", __ -> myHandler.getDefinitions()).build()
).filter(HandlerFilterFunction.ofResponseProcessor((serverRequest, serverResponse) ->
// TODO: Set content type header to application/json
));
}
I tried to clone the response using ServerResponse::from but it doesn't include the response body. Is there another way to do this?

307 redirect with Authorization header

In looking at the Go docs for http it looks like the Authorization header is removed when a response is a 307. Obviously it makes sense for almost every case but is there a way not to remove the Authorization header?
You can modify your http.Client to add the header again after it has been removed using CheckRedirect:
CheckRedirect func(req *Request, via []*Request) error
Since req is the upcoming request, it can be modified before it is sent. After making the changes, return nil to indicate that the request should still be sent.
Since this is a change to the http client instead of the request, you should check that this redirect is only used for the one URL where you need it (in case you use that client to do other requests).
You client definition could look like this:
http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// you can check old responses for a status code
if len(via) != 0 && via[0].Response.StatusCode == http.StatusTemporaryRedirect {
req.Header.Add("Authorization", "some-value")
}
return nil
},
}

Fetch POST Parameters in Golang with header as application/json

I am new to golang and trying to create REST API with POST Method using httprouter (https://github.com/julienschmidt/httprouter).
I am using simple raw request with header as Content-Type : application/json.
I have tried hard but not getting way to fetch raw query parameters.
req.FormValue("name") or req.Form.Get("name") is working fine but with header as Content-Type : application/x-www-form-urlencoded
Has anyone tried fetching raw query parameters(with header as Content-Type : application/json)?
use Json decode:
req is *http.Request
decoder := json.NewDecoder(req.Body)
decoder.UseNumber()
err := decoder.Decode(&yourStruct)
You need to grab the query params out of the URL.
// req *http.Request
params := req.URL.Query()
myParam := params["my-query-param"]
docs here

Go http response few headers

I'm want send to user alert if he type wrong password and return it to page were he type password. I'm making it like this
func sendJSONHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
http.ServeFile(w, r, "template/api/api.html")
} else if r.Method == "POST" {
r.ParseForm()
if r.Form["password"][0] == "apiPassword" {
j := struct {
Proxies []string
}{Proxies: code.UP.Proxy}
w.Header().Set("Access-Control-Allow-Origin", corsAddrSite)
json.NewEncoder(w).Encode(j)
} else {
// here is a problem
fmt.Fprintln(w, "<script>alert('Wrong Password')</script>")
http.ServeFile(w, r, "template/api/api.html")
}
}
}
But i'v get http: multiple response.WriteHeader calls error.
How to do it right?
You cannot write to the http.ResponseWriter more than once depending on the HTTP spec.
from the go docs https://golang.org/pkg/net/http/#ResponseWriter
To solve your issue, you could have the script tags inside the template file, or make a new template. You could also tailor the response by adding the alert script before you send it. Maybe with template files.
However a proper solution to this problem might be to have more logic in the actual html served, the front end should display a response based on the status code or response body.

response with appropriate mime type requested with accept

Say I have a route:
Route::get('list',...);
If I call that route with Accept: text/html it should return a view with all the blade hoopla.
If I call that route with Accept: application/json it should return json, Accept: application/xml it will return xml.
And so on...
How do I realise that with Laravel 5.1?
You can handle Accept header using these methods of the Request class:
bool accepts(string|array $contentTypes)
If you just care about Json and HTML there is
bool acceptsJson() / bool wantsJson()
bool acceptsHtml()

Resources