Home > Backend Development > Golang > How Can I Serve Static HTML Files Using Go's `net/http` Package?

How Can I Serve Static HTML Files Using Go's `net/http` Package?

Mary-Kate Olsen
Release: 2024-12-17 11:48:25
Original
680 people have browsed it

How Can I Serve Static HTML Files Using Go's `net/http` Package?

Serving Static HTML Files with Go Web Servers

In Go, leveraging the net/http package offers a straightforward approach for serving static HTML files. Execute the following steps:

  1. Import the essential libraries:

    import (
        "net/http"
    )
    Copy after login
  2. Designate the static file's directory:

    http.Handle("/", http.FileServer(http.Dir("./static")))
    Copy after login

    Consider that the static files reside in a directory named "static" within the project's root directory. If you desire a different directory, adjust the path accordingly.

  3. Initialize the web server:

    http.ListenAndServe(":3000", nil)
    Copy after login

    This will allow access to your HTML file by navigating to http://localhost:3000/ in your preferred browser.

Important Notes:

  • Modifications made to the HTML file outside the Go program will be reflected when serving the file.
  • If you want to serve files from a URL different than "/", you can utilize the http.StripPrefix function:

    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
    Copy after login

The above is the detailed content of How Can I Serve Static HTML Files Using Go's `net/http` Package?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template