emptygif
ภาษา: ไทย

ภาษาและเฟรมเวิร์กทั้งหมด

Go standard library (net/http) Go

ตัวอย่างโค้ด Go สำหรับ Go standard library (net/http) ที่ตอบคำขอไปยัง /pixel.gif ด้วย GIF ว่าง ซึ่งถอดรหัสเพียงครั้งเดียวตอนเริ่มทำงาน

Go standard library (net/http) Go

ไฟล์
main.go
รัน
go run .
package main

import (
	"encoding/base64"
	"log"
	"net/http"
)

var gif, _ = base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")

func main() {
	// Go 1.22+ method-aware pattern; GET also answers HEAD.
	http.HandleFunc("GET /pixel.gif", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "image/gif")
		w.Header().Set("Cache-Control", "no-store")
		w.Write(gif) // small bodies get Content-Length automatically
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

เรารันตัวอย่างโค้ดนี้และเทียบไบต์ที่ได้กลับมาแล้ว

ตรวจสอบ

curl -sI http://localhost:8080/pixel.gif

เว็บไซต์ทางการ: Go standard library (net/http)

เพิ่มเติมใน Go