How to add images and media to HTML pages served by a Go web server?

To add images and media to HTML pages served by a Go web server, you can follow these steps:

  1. Create a folder in your Go project directory to store your images and media files. For example, you can create a folder named "static" or "assets". Place your files inside this folder.

  2. Import the "net/http" package in your Go file to handle HTTP requests and responses.

import ( "net/http" )
  1. Create a file server using the "http.FileServer" function, pointing it to the directory where your static files are stored.
fs := http.FileServer(http.Dir("static"))
  1. Register a handler for serving the static files. Use the "http.Handle" function to specify the route and the file server created earlier.
http.Handle("/static/", http.StripPrefix("/static/", fs))

In the example above, any request starting with "/static/" will be handled by the file server.

  1. Start the web server and listen on a specific port.
http.ListenAndServe(":8080", nil)

This will start the server on port 8080, allowing you to access your web page using "http://localhost:8080".

  1. In your HTML file, use the appropriate HTML tags to display the images and media files. For example:
<img src="/static/image.jpg" alt="My Image">

In the example above, the image called "image.jpg" will be displayed on the web page. Since the route is set to "/static/" in the Go code, any file within the "static" folder can be accessed using that route.

By following these steps, you can add images and media to your HTML pages served by a Go web server.