亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
? 1. Set up a basic HTTP server
? 2. Add multiple routes
? 3. Serve static files (like HTML, CSS, JS)
? 4. Use a custom server for better control
Tips & Best Practices
Home Backend Development Golang How to build a simple web server in Golang?

How to build a simple web server in Golang?

Aug 01, 2025 am 07:02 AM
web server golang

Import the net/http package and define the processing function, use http.HandleFunc to register the processor of the root path, and then call http.ListenAndServe(":8080", nil) to start the server; 2. Register independent processors for different paths such as "/about" through http.HandleFunc to achieve multi-routing; 3. Use http.FileServer to combine http.StripPrefix and http.Handle to provide access to the files in the static/ directory through the /static/ path, and optionally define homeHandler to return to the main page; 4. Use http.NewServeMux to create a router multiplexer, and use custom http.Server instances to obtain advanced configuration control capabilities such as timeout and TLS; in summary, a lightweight web server with routing, static file services and extensible configuration can be built through the Go standard library net/http, which is suitable for learning and simple applications, without the need for third-party frameworks.

How to build a simple web server in Golang?

Building a simple web server in Golang is straightforward thanks to the net/http package, which is part of Go's standard library. You don't need external dependencies for basic functionality. Here's how to do it step by step.

How to build a simple web server in Golang?

? 1. Set up a basic HTTP server

Start by importing the required packages and defining a handler function:

 package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World! This is a simple Go web server.")
}

func main() {
    http.HandleFunc("/", helloHandler)
    fmt.Println("Server starting on :8080...")
    http.ListenAndServe(":8080", nil)
}

What this does:

How to build a simple web server in Golang?
  • http.HandleFunc("/", helloHandler) registers the helloHandler function to handle requests to the root path / .
  • http.ListenAndServe(":8080", nil) starts the server on port 8080.
  • The helloHandler writes a simple response to the client.

Run it with:

 go run main.go

Then visit http://localhost:8080 in your browser.

How to build a simple web server in Golang?

? 2. Add multiple routes

You can define different handlers for different paths:

 func aboutHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About page - Built with Go!")
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.HandleFunc("/about", aboutHandler)

    fmt.Println("Server running on http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

Now:

  • GET / → "Hello, World!"
  • GET /about → "About page - Built with Go!"

? 3. Serve static files (like HTML, CSS, JS)

Suppose you have a folder static/ with an index.html file.

 func main() {
    fs := http.FileServer(http.Dir("static/"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))

    http.HandleFunc("/", homeHandler) // Optional: render home page

    fmt.Println("Server on :8080")
    http.ListenAndServe(":8080", nil)
}

With this:

  • Files in static/ are served under /static/...
  • For example, static/index.html → accessible at http://localhost:8080/static/index.html

And your homeHandler could be:

 func homeHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "static/index.html")
}

? 4. Use a custom server for better control

Instead of http.ListenAndServe , use http.Server for timeouts and graceful shutdowns:

 func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", helloHandler)
    mux.HandleFunc("/about", aboutHandler)

    server := &http.Server{
        Addr: ":8080",
        Handler: mux,
    }

    fmt.Println("Server starting on :8080")
    if err := server.ListenAndServe(); err != nil {
        fmt.Printf("Server failed: %v\n", err)
    }
}

This gives you more control over configuration (like timeouts, TLS, etc.).


Tips & Best Practices

  • Always validate input in real apps (headers, query params, body).
  • Avoid nil handler in ListenAndServe if using a custom ServeMux .
  • For production, consider using routers like gorilla/mux or chi , but for learning or simple APIs, net/http is perfect.
  • Handle errors properly (eg, file not found, bad requests).

That's it — you've built a working web server in Go with routing and static file support. It's minimal, fast, and doesn't need a framework.

The above is the detailed content of How to build a simple web server in Golang?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

IIS: An Introduction to the Microsoft Web Server IIS: An Introduction to the Microsoft Web Server May 07, 2025 am 12:03 AM

IIS is a web server software developed by Microsoft to host websites and applications. 1. Installing IIS can be done through the "Add Roles and Features" wizard in Windows. 2. Creating a website can be achieved through PowerShell scripts. 3. Configure URL rewrites can be implemented through web.config file to improve security and SEO. 4. Debugging can be done by checking IIS logs, permission settings and performance monitoring. 5. Optimizing IIS performance can be achieved by enabling compression, configuring caching and load balancing.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Golang vs. Python: The Pros and Cons Golang vs. Python: The Pros and Cons Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

IIS: Key Features and Functionality Explained IIS: Key Features and Functionality Explained May 03, 2025 am 12:15 AM

Reasons for IIS' popularity include its high performance, scalability, security and flexible management capabilities. 1) High performance and scalability With built-in performance monitoring tools and modular design, IIS can optimize and expand server capabilities in real time. 2) Security provides SSL/TLS support and URL authorization rules to protect website security. 3) Application pool ensures server stability by isolating different applications. 4) Management and monitoring simplifies server management through IISManager and PowerShell scripts.

See all articles