Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
Got a question from a Golang newbie. He is asking how to protect certain directory or page from being accessed by the public or getting indexed by search engine.
Since he is using the Go internal web server instead of the Apache and Nginx, therefore, the .htaccess
method will not work.
# disable directory browsing
Options -Indexes
To prevent a page from being accessed, the web server needs to reply with HTTP/1.1 403 Forbidden
status code. Here is the code to do just that. Example adapted from my previous tutorial on how to return HTTP status codes in Golang.
package main
import (
"net/http"
)
func returnCode403(w http.ResponseWriter, r *http.Request) {
// see http://golang.org/pkg/net/http/#pkg-constants
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("403 HTTP status code returned!"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", returnCode403)
http.ListenAndServe(":8080", mux)
}
Executing curl -I localhost:8080
will give you :
HTTP/1.1 403 Forbidden
Date: Wed, 21 Oct 2015 03:12:36 GMT
Content-Length: 30
Content-Type: text/plain; charset=utf-8
Reference :
https://www.socketloop.com/tutorials/golang-how-to-return-http-status-code
See also : Golang : How to return HTTP status code?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.5k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+4.1k Mac/Linux/Windows : Get CPU information from command line
+7.9k Golang : How to flush a channel before the end of program?
+8.7k Golang : Post data with url.Values{}
+20.1k Golang : Smarter Error Handling with strings.Contains()
+7.4k Golang : Get current, epoch time and display by year, month and day
+11.8k Golang : Set up source IP address before making HTTP request
+10k Golang : Human readable time elapsed format such as 5 days ago
+6k How to show different content from website server when AdBlock is detected?
+4.1k Golang : How to get capacity of a slice or array?
+17.8k Golang : How to read JPG(JPEG), GIF and PNG files ?
+18.3k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."