GitBucket
4.21.2
Toggle navigation
Snippets
Sign in
Files
Branches
1
Releases
Issues
1
Pull requests
Labels
Priorities
Milestones
Wiki
Forks
mark.george
/
httpcat
Browse code
Update documentation
1 parent
100c322
commit
b576de25fee56f44da266042bedc6ba2be0b4823
Mark George
authored
on 16 Apr 2022
Patch
Showing
5 changed files
README.md
src/client.go
src/global_options.go
src/proxy.go
src/server.go
Ignore Space
Show notes
View
README.md
httpcat =============== A netcat-like tool for analysing or mocking HTTP requests. My first experiment with Go. ## Usage ``` httpcat <command> [OPTIONS] Commands: client Send an HTTP request proxy Start a reverse HTTP logging proxy server Start a mock HTTP server version Display version Command specific help: httpcat <command> --help ``` ### Global Options The following options apply to all commands. ``` -v, --verbose Show additional details. --headers Show headers and request/status line only (default is everything). --bodies Show bodies only (default is everything). --nocolour Don't use colours (default is requests in blue and responses in red). --notimestamps Don't show timestamps. --noindent Don't indent bodies (currently, only application/json bodies are indented). ``` ## Client Mode Sends an HTTP request to the specified server and displays the response. ### Usage ``` httpcat client [OPTIONS] ``` ### Client Specific Options ``` -u, --url= The URL to send the request to. -H, --header= A header to add to request in the form name:value. Use multiple times for multiple headers. -m, --method=[GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS] HTTP method for request (default: GET). -b, --body= Request body to send. ``` ### Example ``` httpcat client \ --method POST \ --body "Testing 123" \ --header "Content-Type: text/plain" \ --header "Authorization: Bearer abc123" \ --uri http://localhost:8080/api/testing ``` Note that the `\` character in the above example is the line continuation character that allows you to break long lines into smaller lines in most Linux/macOS shells. For the Windows `cmd` shell, use `^` for line continuation. For PowerShell, use <code>`</code> (the backtick character). ## Server Mode Creates a web server with mock routes that listen on specific paths and return specific response bodies. Displays the details of any requests that it receives. ### Usage ``` httpcat server [OPTIONS] ``` ### Server Specific Options ``` -p, --port= Port to listen on. (default: 8080). -r, --route= Route which is made up of a path, a response body, and a response status, all separated by the pipe '|' character. Repeat for additional routes. (default: /|testing 123|200). -c, --cors Enable Cross Origin Resource Sharing (CORS). Allows all requested methods and headers. -H, --header= A header to add to response in the form name:value. Use multiple times for multiple headers. ``` ### Example ``` httpcat server \ --port 8080 \ --route "/hello|Hello World|200" \ --route "/goodbye||204" \ --header "Content-Type: text/plain" \ --cors ``` This creates a web server that listens on port `8080` and responds to any requests to the `/hello` path with the response `Hello World` and response code `200`, and returns an empty response with a `204` code to any requests made to `/goodbye`. The server will allow any requested headers and methods for CORS requests. ## Proxy Mode Creates a reverse proxy that displays all HTTP requests and responses that pass through it. ### Usage ``` httpcat proxy [OPTIONS] ``` ### Proxy Specific Options ``` -p, --port= The port that the proxy listens on. -t, --target= ``` ### Example ``` httpcat proxy --port 8090 --target http://localhost:8080 ``` Any requests sent to port 8090 will be forwarded to `http://localhost:8080` and all requests and responses will be displayed. ## Building ``` cd src go build -o ../httpcat ``` ### Cross Compiling Linux ``` GOOS=linux GOARCH=amd64 go build -o ../httpcat-linux ``` Windows ``` GOOS=windows GOARCH=amd64 go build -o ../httpcat-win64 ``` Intel Mac ``` GOOS=darwin GOARCH=amd64 go build -o ../httpcat-mac-intel ``` M1/ARM64 Mac ``` GOOS=darwin GOARCH=arm64 go build -o ../httpcat-mac-arm64 ``` ## License Zero-Clause BSD License Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
httpcat =============== A netcat like tool for analysing/mocking HTTP requests (from both server and client perspective). My first experiment with Go. ## Usage ``` httpcat [OPTIONS] <command> Application Options: -v, --verbose Show additional details --headers Show headers and request/status line only (default is everything) --bodies Show bodies only (default is everything) --nocolour Don't use colours (default is requests are blue and responses are red) --notimestamps Don't show timestamps Help Options: -h, --help Show this help message Available commands: client Send an HTTP request proxy Start a reverse HTTP logging proxy server Start a mock HTTP server version Display version ``` Get help about a specific command by adding `--help` after the command. Example: ``` httpcat client --help ``` ## Client Mode Sends a request to the specified server and displays the response. ### Usage ``` httpcat [OPTIONS] client [client-OPTIONS] Application Options: -v, --verbose Show additional details --headers Show headers and request/status line only (default is everything) --bodies Show bodies only (default is everything) --nocolour Don't use colours (default is requests are blue and responses are red) --notimestamps Don't show timestamps Help Options: -h, --help Show this help message [client command options] -u, --uri= The URI to send the request to --header= A header to add to request in the form name:value. Use multiple times for multiple headers. -m, --method= HTTP method for request (default: GET) -b, --body= Request body to send ``` ### Example ``` httpcat client --method POST --body TESTING --uri http://localhost:8080/api/testing ``` ## Server Mode Creates mock routes that listen on specific paths and return specific response bodies. Displays the details of any requests that it receives. ### Usage ``` httpcat [OPTIONS] server [server-OPTIONS] Application Options: -v, --verbose Show additional details --headers Show headers and request/status line only (default is everything) --bodies Show bodies only (default is everything) --nocolour Don't use colours (default is requests are blue and responses are red) --notimestamps Don't show timestamps Help Options: -h, --help Show this help message [server command options] -p, --port= Port to listen on. (default: 8080) -r, --route= Route which is made up of a path, a response body, and a response status, all separated by the pipe character. Repeat for additional routes. (default: /|testing|200) -c, --cors Enable Cross Origin Resource Sharing (CORS). -H, --header= A header to add to response in the form name:value. Repeat for additional headers. ``` ### Example ``` httpcat server --port 8080 --route "/hello|Hello World|200" --header "Content-Type:text/plain" ``` This creates a web server that listens on port 8080 and responds to any requests to the `/hello` path with the response `Hello World` and response code `200`. Repeat the `--route` option to add more routes. ## Proxy Mode Creates a reverse proxy that displays all HTTP requests and responses that pass through it. ### Usage ``` httpcat [OPTIONS] proxy [proxy-OPTIONS] Application Options: -v, --verbose Show additional details --headers Show headers and request/status line only (default is everything) --bodies Show bodies only (default is everything) --nocolour Don't use colours (default is requests are blue and responses are red) --notimestamps Don't show timestamps Help Options: -h, --help Show this help message [proxy command options] -p, --port= The port that the proxy listens on. -t, --target= ``` ### Example ``` httpcat proxy --port 8090 --target http://localhost:8080 ``` Any requests sent to port 8090 will be forwarded to `http://localhost:8080` and all requests and responses will be displayed. ## Building ``` cd src go build -o ../httpcat ``` ### Cross Compiling Linux ``` GOOS=linux GOARCH=amd64 go build -o ../httpcat-linux ``` Windows ``` GOOS=windows GOARCH=amd64 go build -o ../httpcat-win64 ``` Intel Mac ``` GOOS=darwin GOARCH=amd64 go build -o ../httpcat-mac-intel ``` M1/ARM64 Mac ``` GOOS=darwin GOARCH=arm64 go build -o ../httpcat-mac-arm64 ``` ## License Zero-Clause BSD License Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Ignore Space
Show notes
View
src/client.go
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main import ( "fmt" "net/http" "os" "strings" ) type ClientCommand struct { URL string `short:"u" long:"url" description:"The URL to send the request to." required:"true"` Headers []string `short:"H" long:"header" description:"A header to add to request in the form name:value. Use multiple times for multiple headers."` Method string `short:"m" long:"method" choice:"GET" choice:"POST" choice:"PUT" choice:"DELETE" choice:"PATCH" choice:"HEAD" choice:"OPTIONS" description:"HTTP method for request." default:"GET"` Body string `short:"b" long:"body" description:"Request body to send."` } func (opts *ClientCommand) Execute(args []string) error { sendRequest(opts) return nil } func sendRequest(opts *ClientCommand) { client := http.Client{} request, _ := http.NewRequest(opts.Method, opts.URL, strings.NewReader(opts.Body)) // add extra headers if specified if len(opts.Headers) > 0 { for _, header := range opts.Headers { if name, value, err := parseHeader(header); err == nil { if globalOptions.Verbose { fmt.Println("Adding request header - " + name + ": " + value) } request.Header.Add(name, value) } else { fmt.Println("The following header is not in the correct format: " + header + "\nCorrect format is: 'name:value'") os.Exit(1) } } } if response, err := client.Do(request); err != nil { fmt.Println("Could not connect to server") } else { defer response.Body.Close() showResponse(response) } }
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main import ( "fmt" "net/http" "os" "strings" ) type ClientCommand struct { URL string `short:"u" long:"url" description:"The URL to send the request to" required:"true"` Headers []string `short:"H" long:"header" description:"A header to add to request in the form name:value. Use multiple times for multiple headers."` Method string `short:"m" long:"method" choice:"GET" choice:"POST" choice:"PUT" choice:"DELETE" choice:"PATCH" choice:"HEAD" choice:"OPTIONS" description:"HTTP method for request" default:"GET"` Body string `short:"b" long:"body" description:"Request body to send"` } func (opts *ClientCommand) Execute(args []string) error { sendRequest(opts) return nil } func sendRequest(opts *ClientCommand) { client := http.Client{} request, _ := http.NewRequest(opts.Method, opts.URL, strings.NewReader(opts.Body)) // add extra headers if specified if len(opts.Headers) > 0 { for _, header := range opts.Headers { if name, value, err := parseHeader(header); err == nil { if globalOptions.Verbose { fmt.Println("Adding request header - " + name + ": " + value) } request.Header.Add(name, value) } else { fmt.Println("The following header is not in the correct format: " + header + "\nCorrect format is: 'name:value'") os.Exit(1) } } } if response, err := client.Do(request); err != nil { fmt.Println("Could not connect to server") } else { defer response.Body.Close() showResponse(response) } }
Ignore Space
Show notes
View
src/global_options.go
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main type GlobalOptions struct { Verbose bool `short:"v" long:"verbose" description:"Show additional details."` HeadersOnly bool `long:"headers" description:"Show headers and request/status line only (default is everything)."` BodiesOnly bool `long:"bodies" description:"Show bodies only (default is everything)."` NoColour bool `long:"nocolour" description:"Don't use colours (default is requests in blue and responses in red)."` NoTimestamps bool `long:"notimestamps" description:"Don't show timestamps."` NoIndent bool `long:"noindent" description:"Don't indent bodies (currently, only application/json bodies are indented)."` } var ( globalOptions = new(GlobalOptions) )
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main type GlobalOptions struct { Verbose bool `short:"v" long:"verbose" description:"Show additional details"` HeadersOnly bool `long:"headers" description:"Show headers and request/status line only (default is everything)"` BodiesOnly bool `long:"bodies" description:"Show bodies only (default is everything)"` NoColour bool `long:"nocolour" description:"Don't use colours (default is requests in blue and responses in red)"` NoTimestamps bool `long:"notimestamps" description:"Don't show timestamps"` NoIndent bool `long:"noindent" description:"Don't indent bodies (currently, only application/json bodies are indented)"` } var ( globalOptions = new(GlobalOptions) )
Ignore Space
Show notes
View
src/proxy.go
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main import ( "fmt" "net/http" "net/http/httputil" "net/url" "strconv" ) type ProxyCommand struct { Port int `short:"p" long:"port" description:"The port that the proxy listens on." required:"true"` Target string `short:"t" long:"target" description:"The URL for the target web server that the proxy forwards requests to." required:"true"` } func (opts *ProxyCommand) Execute(args []string) error { fmt.Println("Proxying port " + strconv.Itoa(opts.Port) + " to " + opts.Target) proxy, err := CreateProxy(opts.Target) if err != nil { panic(err) } http.HandleFunc("/", RequestHandler(proxy)) if err := http.ListenAndServe(":"+strconv.Itoa(opts.Port), nil); err != nil { panic(err) } return nil } func CreateProxy(target string) (*httputil.ReverseProxy, error) { url, err := url.Parse(target) // bad target URL if err != nil { return nil, err } proxy := httputil.NewSingleHostReverseProxy(url) OriginalDirector := proxy.Director proxy.Director = func(req *http.Request) { FixHeaders(url, req) showRequest(req) // send request to target OriginalDirector(req) } proxy.ModifyResponse = func(rsp *http.Response) error { showResponse(rsp) return nil } proxy.ErrorHandler = func(rsp http.ResponseWriter, req *http.Request, err error) { fmt.Println("Error sending request to target server:") fmt.Println(" " + err.Error()) } return proxy, nil } func FixHeaders(url *url.URL, req *http.Request) { // TODO this may be necessary for proxying HTTPS (need to test) req.URL.Host = url.Host req.URL.Scheme = url.Scheme req.Host = url.Host } func RequestHandler(proxy *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) } }
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main import ( "fmt" "net/http" "net/http/httputil" "net/url" "strconv" ) type ProxyCommand struct { Port int `short:"p" long:"port" description:"The port that the proxy listens on." required:"true"` Target string `short:"t" long:"target" descrtiption:"The URL for the target web server that the proxy forwards requests to." required:"true"` } func (opts *ProxyCommand) Execute(args []string) error { fmt.Println("Proxying port " + strconv.Itoa(opts.Port) + " to " + opts.Target) proxy, err := CreateProxy(opts.Target) if err != nil { panic(err) } http.HandleFunc("/", RequestHandler(proxy)) if err := http.ListenAndServe(":"+strconv.Itoa(opts.Port), nil); err != nil { panic(err) } return nil } func CreateProxy(target string) (*httputil.ReverseProxy, error) { url, err := url.Parse(target) // bad target URL if err != nil { return nil, err } proxy := httputil.NewSingleHostReverseProxy(url) OriginalDirector := proxy.Director proxy.Director = func(req *http.Request) { FixHeaders(url, req) showRequest(req) // send request to target OriginalDirector(req) } proxy.ModifyResponse = func(rsp *http.Response) error { showResponse(rsp) return nil } proxy.ErrorHandler = func(rsp http.ResponseWriter, req *http.Request, err error) { fmt.Println("Error sending request to target server:") fmt.Println(" " + err.Error()) } return proxy, nil } func FixHeaders(url *url.URL, req *http.Request) { // TODO this may be necessary for proxying HTTPS (need to test) req.URL.Host = url.Host req.URL.Scheme = url.Scheme req.Host = url.Host } func RequestHandler(proxy *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) } }
Ignore Space
Show notes
View
src/server.go
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main import ( "fmt" "net/http" "os" "strconv" ) type ServerCommand struct { Port int `short:"p" long:"port" description:"Port to listen on." default:"8080"` Routes []string `short:"r" long:"route" description:"Route which is made up of a path, a response body, and a response status, all separated by the pipe '|' character. Repeat for additional routes." default:"/|testing 123|200"` Cors bool `short:"c" long:"cors" description:"Enable Cross Origin Resource Sharing (CORS). Allows all requested methods and headers."` Headers []string `short:"H" long:"header" description:"A header to add to response in the form name:value. Use multiple times for multiple headers."` } var ( serverOptions *ServerCommand ) func (opts *ServerCommand) Execute(args []string) error { serverOptions = opts // parse custom headers if provided if len(opts.Headers) > 0 { for _, header := range opts.Headers { if _, _, err := parseHeader(header); err != nil { fmt.Println("The following header is not in the correct format: " + header + "\nCorrect format is: 'name:value'") os.Exit(1) } } } fmt.Println("HTTP server listening on port " + strconv.Itoa(opts.Port) + "\n") if len(opts.Routes) > 0 { fmt.Println("Routes:") for _, route := range opts.Routes { if path, _, _, err := parseRoute(route); err == nil { fmt.Println(" " + path) http.HandleFunc(path, serverRequestHandler) } else { fmt.Println("The following route is not in the correct format: " + route + "\nCorrect format is: \"/path|response body|status code\"") os.Exit(1) } } fmt.Println() } if err := http.ListenAndServe(":"+strconv.Itoa(opts.Port), nil); err != nil { fmt.Fprintf(os.Stderr, "Could not start server. Is port %d available?\n", opts.Port) os.Exit(1) } return nil } func serverRequestHandler(rsp http.ResponseWriter, req *http.Request) { path := req.RequestURI body := bodies[path] code := statuses[path] showRequest(req) // CORS preflight if serverOptions.Cors && req.Method == http.MethodOptions { // was the OPTIONS request actually a CORS request? if secFetchMode := req.Header.Get("Sec-Fetch-Mode"); secFetchMode == "cors" { if globalOptions.Verbose { fmt.Println("Responding to CORS preflight") } if origin := req.Header.Get("Origin"); origin != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Origin: " + origin) } // allow the origin rsp.Header().Set("Access-Control-Allow-Origin", origin) if headers := req.Header.Get("Access-Control-Request-Headers"); headers != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Headers: " + headers) } // allow any requested headers rsp.Header().Set("Access-Control-Allow-Headers", headers) } if method := req.Header.Get("Access-Control-Request-Method"); method != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Methods: " + method) } // allow any requested methods rsp.Header().Set("Access-Control-Allow-Methods", method) } if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Max-Age: " + "600") } // allow browser to reuse the permissions for 10 minutes rsp.Header().Set("Access-Control-Max-Age", "600") rsp.WriteHeader(200) return } else { if globalOptions.Verbose { fmt.Println("CORS preflight did not contain 'Origin' header!") } rsp.Header().Set("Content-Type", "text/plain") rsp.WriteHeader(400) fmt.Fprint(rsp, "Origin header was not provided") return } } } // add custom headers if provided if len(serverOptions.Headers) > 0 { for name, value := range headers { if globalOptions.Verbose { fmt.Println("Adding response header - " + name + ": " + value) } rsp.Header().Set(name, value) } } // add CORS allow-origin header if serverOptions.Cors && req.Method != http.MethodOptions { if origin := req.Header.Get("Origin"); origin != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Origin: " + origin) } rsp.Header().Set("Access-Control-Allow-Origin", origin) } } // add status line rsp.WriteHeader(code) // add body fmt.Fprint(rsp, body) }
/** Author: Mark George <mark.george@otago.ac.nz> License: Zero-Clause BSD License */ package main import ( "fmt" "net/http" "os" "strconv" ) type ServerCommand struct { Port int `short:"p" long:"port" description:"Port to listen on." default:"8080"` Routes []string `short:"r" long:"route" description:"Route which is made up of a path, a response body, and a response status, all separated by the pipe '|' character. Repeat for additional routes." default:"/|testing|200"` Cors bool `short:"c" long:"cors" description:"Enable Cross Origin Resource Sharing (CORS)."` Headers []string `short:"H" long:"header" description:"A header to add to response in the form name:value. Repeat for additional headers."` } var ( serverOptions *ServerCommand ) func (opts *ServerCommand) Execute(args []string) error { serverOptions = opts // parse custom headers if provided if len(opts.Headers) > 0 { for _, header := range opts.Headers { if _, _, err := parseHeader(header); err != nil { fmt.Println("The following header is not in the correct format: " + header + "\nCorrect format is: 'name:value'") os.Exit(1) } } } fmt.Println("HTTP server listening on port " + strconv.Itoa(opts.Port) + "\n") if len(opts.Routes) > 0 { fmt.Println("Routes:") for _, route := range opts.Routes { if path, _, _, err := parseRoute(route); err == nil { fmt.Println(" " + path) http.HandleFunc(path, serverRequestHandler) } else { fmt.Println("The following route is not in the correct format: " + route + "\nCorrect format is: \"/path|response body|status code\"") os.Exit(1) } } } if err := http.ListenAndServe(":"+strconv.Itoa(opts.Port), nil); err != nil { fmt.Fprintf(os.Stderr, "Could not start server. Is port %d available?\n", opts.Port) os.Exit(1) } return nil } func serverRequestHandler(rsp http.ResponseWriter, req *http.Request) { path := req.RequestURI body := bodies[path] code := statuses[path] showRequest(req) // CORS preflight if serverOptions.Cors && req.Method == http.MethodOptions { // was the OPTIONS request actually a CORS request? if secFetchMode := req.Header.Get("Sec-Fetch-Mode"); secFetchMode == "cors" { if globalOptions.Verbose { fmt.Println("Responding to CORS preflight") } if origin := req.Header.Get("Origin"); origin != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Origin: " + origin) } // allow the origin rsp.Header().Set("Access-Control-Allow-Origin", origin) if headers := req.Header.Get("Access-Control-Request-Headers"); headers != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Headers: " + headers) } // allow any requested headers rsp.Header().Set("Access-Control-Allow-Headers", headers) } if method := req.Header.Get("Access-Control-Request-Method"); method != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Methods: " + method) } // allow any requested methods rsp.Header().Set("Access-Control-Allow-Methods", method) } if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Max-Age: " + "600") } // allow browser to reuse the permissions for 10 minutes rsp.Header().Set("Access-Control-Max-Age", "600") rsp.WriteHeader(200) return } else { if globalOptions.Verbose { fmt.Println("CORS preflight did not contain 'Origin' header!") } rsp.Header().Set("Content-Type", "text/plain") rsp.WriteHeader(400) fmt.Fprint(rsp, "Origin header was not provided") return } } } // add custom headers if provided if len(serverOptions.Headers) > 0 { for name, value := range headers { if globalOptions.Verbose { fmt.Println("Adding response header - " + name + ": " + value) } rsp.Header().Set(name, value) } } // add CORS allow-origin header if serverOptions.Cors && req.Method != http.MethodOptions { if origin := req.Header.Get("Origin"); origin != "" { if globalOptions.Verbose { fmt.Println("Adding CORS response header - Access-Control-Allow-Origin: " + origin) } rsp.Header().Set("Access-Control-Allow-Origin", origin) } } // add status line rsp.WriteHeader(code) // add body fmt.Fprint(rsp, body) }
Show line notes below