MIME type (“text/plain”) mismatch (X-Content-Type-Options: nosniff) - go

I was using golang net/http funcions and had no errors, but I needed custom URL so I implemented gorilla/mux router and now getting errors like this:
The resource from “http://localhost:8080/styles.css” was blocked due to MIME type (“text/plain”) mismatch (X-Content-Type-Options: nosniff).
The resource from “http://localhost:8080/main.js” was blocked due to MIME type (“text/plain”) mismatch (X-Content-Type-Options: nosniff).
The resource from “http://localhost:8080/base.js” was blocked due to MIME type (“text/plain”) mismatch (X-Content-Type-Options: nosniff).
code before:
http.Handle("/transcode", http.HandlerFunc(transcodeHandler))
http.Handle("/tctype", http.HandlerFunc(tctypeHandler))
http.Handle("/sse/dashboard", lp.B)
http.Handle("/upload", http.HandlerFunc(uploadHandler))
http.Handle("/", http.FileServer(http.Dir("views")))
fmt.Println("Listening on port: 8080...")
log.Fatalf("Exited: %s", http.ListenAndServe(":8080", nil))
code after:
r := mux.NewRouter()
r.Handle("/ngx/mapping/{name}", http.HandlerFunc(ngxMappingHandler))
r.Handle("/transcode", http.HandlerFunc(transcodeHandler))
r.Handle("/tctype", http.HandlerFunc(tctypeHandler))
r.Handle("/sse/dashboard", lp.B)
r.Handle("/upload", http.HandlerFunc(uploadHandler))
r.Handle("/", http.FileServer(http.Dir("views")))
fmt.Println("Listening on port: 8080...")
log.Fatalf("Exited: %s", http.ListenAndServe(":8080", r))

Related

Getting MIME type ('text/plain') error in Golang while serving CSS

I am building my first Go web project and I am getting this error on the browser console when I load my page
Refused to apply style from 'http://localhost:8080/static/css/processor-auth.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I am not sure what I am doing wrong because I have already added this code to load the static files
http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("static"))))
This is how my main.go file looks like:
package main
import(
"net/http"
"os"
"html/template"
"github.com/julienschmidt/httprouter"
)
// Auth struct handler
type auth struct{}
func (auth *auth) ServeHTTP(w http.ResponseWriter, r *http.Request){
wd,_:= os.Getwd()
t := template.Must(template.ParseFiles(wd+"/templates/processor/auth.html"))
err:=t.Execute(w,nil)
if err !=nil{
http.Error(w,"Could not execute template",500)
}
}
func main(){
router:= httprouter.New()
// set the static files
http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("static"))))
router.Handler("GET","/auth",&auth{})
server := http.Server{
Addr:"127.0.0.1:8080",
Handler:router,
}
server.ListenAndServe()
}
Edit: Solved the issue
Since I was using httprouter as my multiplexer I could not use
http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("static"))))
I had to update to the httprouter's ServeFiles function and update the code to
router.ServeFiles("/static/*filepath",http.Dir("static"))

How to use http.Get request inside handler func

How to make http.Get request inside of handler func?
For example, this simple code "should" return blank page in localhost:8080 browser but it go nuts. What I have missed in school?
package main
import "net/http"
func index(w http.ResponseWriter, r *http.Request) {
_, err := http.Get("www.google.com")
if err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil)
}
The problem is that you should use a protocol (e.g. https://) in the Get function:
_, err := http.Get("https://www.google.com")
The error in you original code is Get www.google.com: unsupported protocol scheme "".
http.Get() expects a URL, and www.google.com is not a URL; a URL begins with a scheme. Even though it is common to type "www.google.com" into a browser, it's still not a full URL; friendly browsers automatically prepend "http://" or "https://" before issuing the request. http.Get() isn't going to do that; it expects a well-formed URL to begin with.

acme: authorization error for <domain> (acme/autocert)

When running the following code I get the error:
acme: authorization error for domain (where domain is replaced by my
actual domain)
Has anyone else had this issue? The error returned does not give that much insight.
package main
import (
"crypto/tls"
"net/http"
"golang.org/x/crypto/acme/autocert"
)
func main() {
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(<domain>), //your domain here
Cache: autocert.DirCache("cache"), //folder for storing certificates
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world"))
})
server := &http.Server{
Addr: ":8086",
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
}
if err := server.ListenAndServeTLS("", ""); err != nil {
print(err.Error())
}
}
Perhaps your server is on port 8086 and the tls challenge is on port 443?
Try instead serving on port 443 (You may have to setcap your binary to allow it to do this).
See this issue on lets encrypt:
https://github.com/letsencrypt/acme-spec/issues/33

Golang route not working

I just started to get into golang and as I plan to host at least two websites, I chose to use Mux to display different routes by "filtering" domains. Whenever I try to access my main route, it just gives me an 404 error. (Also, the fact that the "www" part is absent is perfectly normal. I don't type that to access the site).
But if I launch the server as a file server, I can access my files, so the server in itself is working I guess
func redirect(w http.ResponseWriter, req *http.Request) {
target := "https://" + req.Host + req.URL.Path
http.Redirect(w, req, target,
http.StatusTemporaryRedirect)
}
func main() {
go http.ListenAndServe(":80", http.HandlerFunc(redirect)) // Redirection
// Serveur sécurisé
r := mux.NewRouter()
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("/root/go/src/web/static/"))))
s := r.Host("echecderi.me").Subrouter()
s.HandleFunc("/", indexEchec)
http.ListenAndServeTLS(":443", "domain-crt.pem", "domain-key.pem", nil)
}
func indexEchec(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Echec de rime</h1> </br> <img src=\"/static/echecderime/echec.gif\">")
}
I think you need to give r as the last parameter to http.ListenAndServeTLS.
you can also use a http.server instance
//create server instance
server := http.Server{
Addr: ":443",
TLSConfig: tlsConfig(cert),
}
rtr := mux.NewRouter()
rtr.HandleFunc("/profile", HandlerProfile).Methods("GET")
//rtr.HandleFunc( other routes...
//pass mux handler to server
server.Handler = rtr
server.ListenAndServeTLS("", "")

Go Nil Dereference Error When Testing HTTP Request

I am trying to test a HTTP request in my Go library. Object which makes the call accepts a HTTP client object via dependency injection so in my test I am mocking the HTTP client like this:
func TestMyObject(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, mockJSONResponse)
}))
defer server.Close()
// Make a transport that reroutes all traffic to the example server
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}
// Make a http.Client with the transport
httpClient := &http.Client{Transport: transport}
// I am passing the httpClient to my object
}
Here is how the HTTP request is made within my object:
// Make - makes a prepared HTTP request
func (ir *MyObject) Make() *http.Response {
if ir.Err != nil {
return nil
}
ir.resp, ir.Err = ir.Client.Do(ir.req)
runtime.SetFinalizer(ir, func(ir *MyObject) {
ir.resp.Body.Close()
})
ir.logReqRes()
ir.checkErrorResponse()
return ir.resp
}
I am getting nil pointer dereference error though:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
In this function (I am trying to log the response):
// Logs request and response
func (ir *MyObject) logReqRes() {
log.Print("AAAAAAA")
log.Print(ir.resp)
log.Print("AAAAAAA")
if reqInfo, err := httputil.DumpRequest(ir.req, true); err == nil {
log.Print("Logging request:")
log.Print(string(reqInfo))
}
if respInfo, err := httputil.DumpResponse(ir.resp, true); err == nil {
log.Print("Logging response:")
log.Print(string(respInfo))
}
}
As you can see, ir.resp is nil for some reason. Any ideas?
Ok. I found an issue. Better logging of errors actually showed that my mistake was very simple.
I was passing this as a URL to mocked HTTP client:
host/api/v1/tokens/
Which was resulting in this error:
Post host/api/v1/tokens/: unsupported protocol scheme
Apparently the URL must include a proper HTTP scheme (http://) even when you are using a test server.

Resources