The resource was recognized as a stylesheet but was delivered with the MIME type text/plain in golang

I am encountering an issue while developing my webpage using golang. server file (main.go):

package main

import (
    "net/http"
    "io/ioutil"
    "strings"
    "log"
)

type MyHandler struct {
}

func (this *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    path := r.URL.Path[1:]
    log.Println(path)
    data, err := ioutil.ReadFile(string(path))

    if err == nil {
        var contentType string

        if strings.HasSuffix(path, ".css") {
            contentType = "text/css"
        } else if strings.HasSuffix(path, ".html") {
            contentType = "text/html"
        } else if strings.HasSuffix(path, ".js") {
            contentType = "application/javascript"
        } else if strings.HasSuffix(path, ".png") {
            contentType = "image/png"
        } else if strings.HasSuffix(path, ".svg") {
            contentType = "image/svg+xml"
        } else {
            contentType = "text/plain"
        }

        w.Header().Add("Content Type", contentType)
        w.Write(data)
    } else {
        w.WriteHeader(404)
        w.Write([]byte("404 Mi amigo - " + http.StatusText(404)))
    }
}

func main() {
    http.Handle("/", new(MyHandler))
    http.ListenAndServe(":8080", nil)
}

When I visit http://localhost:8080/templates/home.html I am facing issues which can be seen in this screenshot. Why is my page not loading properly? Where is the CSS file? Why do I get the error "Resource interpreted as Stylesheet but transferred with MIME type text/plain:" even though I have specified the content type in main.go?

Answer №1

The root of your issue is fairly straightforward: You should utilize Content-Type rather than Content Type.

Nevertheless, a more efficient method to pair MIME types with file extensions in Go is through the utilization of the mime standard library package. I strongly recommend incorporating this into your workflow.

Answer №2

as mentioned by "Milo Christiansen", using mime can be beneficial in this scenario. It is worth noting that utilizing io.Copy instead of ioutil.ReadFile may result in greater efficiency (especially if the stream copy can take place at the kernel level).

package main

import (
    "io"
    "log"
    "mime"
    "net/http"
    "os"
    "path/filepath"
)

func main() {
    http.HandleFunc("/", ServeFile)
    log.Fatal(http.ListenAndServe(":8400", nil))
}

func ServeFile(resp http.ResponseWriter, req *http.Request) {
    path := filepath.Join("./resource/", req.URL.Path)
        
    file, err := os.Open(path)
    if err != nil {
        http.Error(resp, err.Error(), http.StatusNotFound)
        return
    }

    if contentType := mime.TypeByExtension(filepath.Ext(path)); len(contentType) > 0 {
        resp.Header().Add("Content-Type", contentType)
    }

    io.Copy(resp, file)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...

The behavior of Material-UI Drawer varies when used on tablets

Encountering some strange issues with the Material-UI drawer component. It's scrolling horizontally on my iPad, while it scrolls vertically on my MacBook and Android Phone. Expected Result on MacBook: https://i.sstatic.net/txBDf.png On my MacBook, it ...

Adjust the CSS of a dynamically generated jQuery checkbox button in real-time

I am working on a project where I am creating a series of jQuery checkboxes dynamically within a loop. Here is how I am doing it: var checkbox = $('<input>').attr({type: 'checkbox', id: checkbox_id); panel.append(checkbox); panel ...

Unable to click on element in Firefox browser

Encountering an issue with the following error message: Element is not clickable at point (791, 394). Other element would receive the click: Command duration or timeout: 66 milliseconds Any ideas on what's causing this? Using selenium web driver ve ...

What is the best way to initially conceal content and then reveal it only after an ajax call is made?

Currently, I have a situation where content is revealed after the callback function of a .js library (typed.js) executes. Here is the script I am using: Javascript $(function(){ $("#logo-black").typed({ strings: ["Nothing^450&Co^250.^500" ...

What is the best way to perfectly align an SVG inside its container?

Is there a way to horizontally center this SVG within .svg_wrapper? .svg_wrapper { border: 1px solid grey; width: 200px; } <div class="svg_wrapper"> <svg viewBox="0 0 600 425"> <path d="M 175, 175 m 0, -75 a 75,75 0 1,0 ...

Tips for aligning a title to the bottom when its length varies

I am facing a design challenge where I need to align a header with content in a different column. The header's length can vary, so I need to figure out how to align the border-bottom consistently. (The code snippet below is just for illustration pur ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

I am experimenting with showcasing a series of Bootstrap div elements, each containing a dynamic carousel of images sourced from a database along with additional information

My image display is working fine, but the other divs are appearing within the first div and the additional information like title and description are not showing. I'm aiming to have six rows, each with two columns, displaying a carousel of images and ...

Responsive CSS for symmetrically-aligned DIVs that float on screens of varying widths

[ 1 ] [ 2 ] [ 3 ] [ 4 ] My design features four floating DIVs, each set to float left with a width and height of 128px. When the screen is narrowed, the last DIV correctly moves to the next line: [ 1 ] [ 2 ] [ 3 ] [ 4 ] However, I want the last two bl ...

Colorful background visuals without any text

Can you achieve a background color effect using Stylus without any text? span { width: 5px; height: 5px; } span.red { background-color: #f00; } <span class="red"></span> ...

cusel.js encountered an error due to attempting to use the 'in' operator to search for 'using' within the specified error

I attempted to implement the cusel.js (styled selects) library on my select elements, but unfortunately it's not functioning as expected. The selects change visually, however when I try to scroll through the options using jscrollpane, an error that I ...

When the width is reduced to a certain point, the display will change to inline-block, preserving the layout structure

My goal is to maintain a two-column layout for my container boxes, even when the browser width is minimized to 600px in my fiddle. The issue arises with the CSS rule display: inline-block causing the boxes to stack into a single column. Important point: I ...

How do I go about extracting and presenting the JSON data from the ESPN API?

In my current project, I am trying to utilize the jQuery library to work with API JSON data. Even though I am experienced in parsing JSON in PHP, I want to explore doing it with jQuery this time around. The goal is to extract information about each of the ...

Positioning <tr> elements with absolute precision within a intricate layout

I am faced with the challenge of developing a complex UI control. The structure consists of a left-side TreeTable component, implemented using a <table> element, and a right-side SVG component that displays data corresponding to each row of the left ...

Changing the content of a PHP div with an Ajax callback inside another Ajax callback?

In the index.php file, there is a script that triggers an ajax call when a header element is clicked. This call sends a $selection variable to ajax.php, which then replaces #div1 with the received HTML data. <script> $(document).ready(function(){ ...

Highlighting the active nav-item in Bootstrap-5 is proving to be a challenge

I'm having trouble with the Bootstrap navbar. I want to change the color of the active nav-link, but it's not working as expected. I am currently using Bootstrap-5. Below is the CSS code I have: .nav-link { color: #666777; font-weight: 4 ...

Error in Angular 2: The app.component.html file triggered an exception at line 1, character 108 due to excessive recursion

After successfully setting up the Angular 2 quickstart and connecting to an express server, I encountered a problem when switching from using the template property to component templateUrl. I have created a Plunker to showcase this issue: Plunker Demo imp ...

What is the best method for storing a variety of HTML form data in a database?

I am currently working on developing a survey system that includes the feature of creating various types of questions through a drag & drop HTML form builder. The idea is for a client to create their survey form, which will then be stored in a database tab ...

What advantages does using ImageMagick to resize images offer compared to using CSS?

My Ruby on Rails application has a feature that allows users to upload images. I have discovered that Active Storage can utilize ImageMagick to resize images using this code: model.image.variant(resize: "100X100") However, resizing images can also be ach ...