目次
Set up a basic HTTP server
Handle different routes
Serve static files
Improve structure with a custom handler
ホームページ バックエンド開発 Golang GolangでシンプルなWebサーバーをどのように構築しますか?

GolangでシンプルなWebサーバーをどのように構築しますか?

Aug 18, 2025 am 10:28 AM
go ウェブサーバー

是的,使用Go的net/http包可以轻松构建一个简单的Web服务器,只需几行代码即可实现路由处理、静态文件服务和结构化处理器,通过http.ListenAndServe启动服务器并监听指定端口,最终运行go run main.go并在浏览器访问http://localhost:8080即可看到效果,整个过程无需外部依赖且适合学习和小型工具开发。

How do you build a simple web server in Golang?

Building a simple web server in Go is straightforward thanks to the built-in net/http package. You don’t need external dependencies for basic functionality. Here’s how to create a minimal but functional web server.

Set up a basic HTTP server

The core of a Go web server is the http.ListenAndServe function, which starts a server on a specified port and listens for incoming requests.

package main

import (
    "fmt"
    "net/http"
)

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

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

This code:

  • Registers a handler for the root path (/) using http.HandleFunc.
  • Uses an anonymous function to write a response.
  • Starts the server on port 8080.

Run it with go run main.go, then visit http://localhost:8080 in your browser.

Handle different routes

You can register multiple routes easily:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the home page!")
})

http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "This is the about page.")
})

http.HandleFunc("/user/", func(w http.ResponseWriter, r *http.Request) {
    path := r.URL.Path
    username := path[len("/user/"):] // Extract username from path
    fmt.Fprintf(w, "User profile: %s", username)
})

Note that Go’s default multiplexer matches prefixes for routes ending in /, so /user/alex will trigger the third handler.

Serve static files

To serve static assets like CSS, JavaScript, or images, use http.FileServer:

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

Place your files in a folder named static, and they’ll be accessible at /static/filename.ext.

Improve structure with a custom handler

Instead of defining everything in main, you can define named handler functions:

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home page")
}

func jsonHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, `{"message": "Hello from JSON"}`)
}

func main() {
    http.HandleFunc("/", homeHandler)
    http.HandleFunc("/json", jsonHandler)

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

This makes your code more modular and testable.

A few practical notes:

  • Always handle errors from ListenAndServe—it won’t return unless there’s an error.
  • The second argument in ListenAndServe is for a custom router. Passing nil uses the default http.DefaultServeMux.
  • For production use, consider timeouts, graceful shutdowns, and middleware, but this basic version is perfect for learning or small tools.

Basically, that’s all it takes to get a working web server in Go. It’s simple, fast, and requires no extra tools.

以上がGolangでシンプルなWebサーバーをどのように構築しますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

ホットトピック

Golangの環境変数をどのように操作しますか? Golangの環境変数をどのように操作しますか? Aug 19, 2025 pm 02:06 PM

goprovides-built-built-insupportfor handlingenvironmentvariablesviatheospackage、developerstoread、set、andmanageenvironmentdatasecurelylelyandyly.toreadavariable、useos.getenv( "key")、whoreturnsenemptringtringifthesnoteset、lo

GOでカスタムエラータイプを作成および使用する方法 GOでカスタムエラータイプを作成および使用する方法 Aug 11, 2025 pm 11:08 PM

GOでは、カスタムエラータイプを作成して使用すると、エラー処理の表現力とデブガブルが向上します。答えは、エラー()メソッドを実装する構造を定義することにより、カスタムエラーを作成することです。たとえば、ValidationErrorにはフィールドとメッセージフィールドが含まれ、フォーマットされたエラー情報を返します。次に、関数でエラーを返すことができ、異なるロジックを実行するために、タイプアサーションまたはエラーを使用して特定のエラータイプを検出できます。また、構造化されたデータ、差別化処理、ライブラリエクスポート、またはAPI統合を必要とするシナリオに適したカスタムエラーに適したカスタムエラーなどの行動方法を追加することもできます。単純な場合、error.new、およびerrnotfoundなどの事前定義されたエラーを使用して、比較可能にすることができます

GOでジェネリックLRUキャッシュを実装する方法 GOでジェネリックLRUキャッシュを実装する方法 Aug 18, 2025 am 08:31 AM

Go GenericsとContainer/Listを使用して、スレッドセーフLRUキャッシュを実現します。 2。コアコンポーネントには、マップ、双方向リンクリスト、ミューテックスロックが含まれます。 3.操作を取得して追加し、O(1)の時間の複雑さを伴うロックを介して同時実行セキュリティを確保します。 4.キャッシュがいっぱいになると、最長の未使用のエントリが自動的に排除されます。 5。例では、容量が3のキャッシュが最も長く使用されていない「B」を正常に排除しました。この実装は、一般的で効率的でスケーラブルなものを完全にサポートします。

GOアプリケーションで信号をどのように処理しますか? GOアプリケーションで信号をどのように処理しますか? Aug 11, 2025 pm 08:01 PM

GOアプリケーションで信号を処理する正しい方法は、OS/信号パッケージを使用して信号を監視し、エレガントなシャットダウンを実行することです。 1.信号を使用して、sigint、sigterm、その他の信号をチャネルに送信します。 2。ゴルチンでメインサービスを実行し、待機信号をブロックします。 3.信号を受信した後、Context.WithTimeOutを介してタイムアウトを使用してエレガントなシャットダウンを実行します。 4.データベース接続の閉鎖やバックグラウンドゴルウチンの停止などのリソースをクリーンアップします。 5.信号を使用して、必要に応じてデフォルトの信号動作を復元して、プログラムをKubernetesおよびその他の環境で確実に終了できることを確認します。

Goでのクロスプラットフォームパス操作にPATH/FILEPATHを使用する方法 Goでのクロスプラットフォームパス操作にPATH/FILEPATHを使用する方法 Aug 08, 2025 pm 05:29 PM

usefilepath.join()tosafelyconstructpathswithcorrectos-specificseparators.2.usefilepath.clean()toremoveredundantelementslikelike ".." and "。"。3.usefilepath.split()toseparatedirectoryandfilecomponents.4.usefilepath.dir()

Goの関数をどのように定義し、呼び出しますか? Goの関数をどのように定義し、呼び出しますか? Aug 14, 2025 pm 06:22 PM

GOでは、機能の定義と呼び出し関数はFUNCキーワードを使用し、固定構文に従って、最初に回答を明確にします。関数定義には、名前、パラメータータイプ、リターンタイプ、関数本文を含め、呼び出し時に対応するパラメーターを渡す必要があります。 1. funcadd(a、bint)int {return b}などの関数を定義する場合、funcfunctionname(params)returnType {} syntaxを使用します。 2。funcdivide(a、bfloat64)(float64、bool){}などの複数の返品値をサポートします。 3。関数の呼び出しは、括弧付きの関数名を直接使用して、結果:= add(3,5)などのパラメーターを渡します。 4.複数の返品値は、変数によって受信できます。

パフォーマンスの比較:Java vs. Go for Backend Services パフォーマンスの比較:Java vs. Go for Backend Services Aug 14, 2025 pm 03:32 PM

gutypivityOffersbetterruntimeperformanceは、特にfori/o-heavyservices、duetoits lightgoroutinesineficientscheduler、whilejava、canslowertart、canmatchgoincpu-boundtasptimization.2.gouseslessme

GOアプリケーションでRSSと原子フィードを解析します GOアプリケーションでRSSと原子フィードを解析します Aug 18, 2025 am 02:40 AM

GoFeedライブラリを使用して、RSSとAtomFeedを簡単に解析します。まず、GogetGithub.com/mmcdole/gofeedを介してライブラリをインストールし、パーサーインスタンスを作成し、ParseurlまたはParseStringメソッドを呼び出して、リモートまたはローカルフィードを解析します。ライブラリは、フォーマットを自動的に認識し、統一されたフィード構造を返します。次に、タイトル、リンク、公開時間などの標準化されたフィールドを取得するために、feed.itemを繰り返します。また、HTTPクライアントのタイムアウトを設定し、解析エラーを処理し、キャッシュ最適化パフォーマンスを使用して、最終的にシンプルで効率的で信頼できる飼料解像度を実現することをお勧めします。

See all articles