2

ctx.Response.Header.Set function is not working for the error case.

Please check the below code,

package main

import "fmt"
import "github.com/valyala/fasthttp"

func main() {
    requestHandler := func(ctx *fasthttp.RequestCtx) {
        ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
        switch string(ctx.Path()) {
        case "/foo":
            fmt.Fprintf(ctx, "Success result")
        case "/bar":
            ctx.Error("Unsupported path", fasthttp.StatusNotFound)
        }
    }
    fasthttp.ListenAndServe(":8080", requestHandler)
}

The /foo URL's response header is,

Server: fasthttp Date: Mon, 16 Apr 2018 04:05:10 GMT

Content-Type: text/plain; charset=utf-8

Content-Length: 14

Access-Control-Allow-Origin: *

But, the /bar 's response header is,

Server: fasthttp

Date: Mon, 16 Apr 2018 04:05:50 GMT

Content-Type: text/plain; charset=utf-8

Content-Length: 16

Access-Control-Allow-Origin header is not applied. Is anything I missed here?

Community
  • 1
  • 1
sprabhakaran
  • 1,615
  • 5
  • 20
  • 36
  • 1
    I'm not familiar with fasthttp nor do I know how a standard implementation should behave but it seems it's what the fasthttp devs [intended](https://github.com/valyala/fasthttp/blob/master/server.go#L895). – mkopriva Apr 16 '18 at 04:32
  • @mkopriva great find. fasthttp's document didn't mention anywhere in the document. So, I am not aware of this. Anyway thanks for your reply. – sprabhakaran Apr 16 '18 at 04:50

1 Answers1

1

The method ctx.Error clears the headers intentionally:

// ...
// Warning: this will reset the response headers and body already set!
func (ctx *RequestCtx) Error(msg string, statusCode int) {...}

The solution is to use other methods:

ctx.SetContentType("text/plain")
ctx.SetStatusCode(404)
ctx.SetBodyString("Unsupported path")
golopot
  • 10,726
  • 6
  • 37
  • 51