← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 7 of 10

मूल HTTP Server

एक HTTP server एक program है जो किसी specific door (port) पर खटखटा रहे visitors (web requests) के लिए बैठकर सुनता है, और हर एक को एक response से जवाब देता है।
Syntax
go
http.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "text")
})
http.ListenAndServe(":port", nil)

Writing a Handler Function

एक HTTP handler func(w http.ResponseWriter, r *http.Request) से मेल खाता एक function है, जहां w को लिखना request करने वाले को response body के रूप में bytes वापस भेजता है।

उदाहरण: Writing a Handler Function

markup
package main

import (
	"fmt"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello from a Go HTTP handler!")
}

func main() {
	http.HandleFunc("/hello", helloHandler)
	fmt.Println("handler registered for /hello")
}

Testing a Handler Without a Real Server

चूंकि इस sandbox में एक असली listener शुरू करना हमेशा के लिए block हो जाएगा, handlers को httptest.NewRecorder और httptest.NewRequest का उपयोग करके सीधे चलाया जा सकता है, जो बिना कोई असली network socket खोले एक HTTP request/response simulate करते हैं।

Note: net/http/httptest बिना असली network port bind किए handlers test करने का standard तरीका है।

उदाहरण: Testing a Handler Without a Real Server

markup
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello, HTTP!")
}

func main() {
	req := httptest.NewRequest(http.MethodGet, "/hello", nil)
	rec := httptest.NewRecorder()

	helloHandler(rec, req)

	fmt.Println("status:", rec.Code)
	fmt.Println("body:", rec.Body.String())
}

Setting a Status Code

w.WriteHeader(code) कोई body लिखे जाने से पहले response के लिए explicitly HTTP status code सेट करता है -- इसे छोड़ने पर पहली write होते ही default 200 OK हो जाता है।

Note: किसी Write/Fprintln call से पहले WriteHeader call करें, क्योंकि status line पहले जानी चाहिए।

उदाहरण: Setting a Status Code

markup
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func notFoundHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprintln(w, "resource not found")
}

func main() {
	req := httptest.NewRequest(http.MethodGet, "/missing", nil)
	rec := httptest.NewRecorder()
	notFoundHandler(rec, req)
	fmt.Println("status:", rec.Code, "body:", rec.Body.String())
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी interactive/CI sandbox में http.ListenAndServe call करना, जो असली network connections का इंतज़ार करते हुए हमेशा के लिए block हो जाता है -- यहां runnable examples को असल में एक listener शुरू करने के बजाय handlers को सीधे call करना चाहिए।
  2. http.HandleFunc से एक ही route pattern को दो बार register करना, जो startup पर panic करता है।
  3. non-200 response चाहिए होने पर body लिखने से पहले एक HTTP status code लिखना भूल जाना -- WriteHeader को Write से पहले call होना चाहिए।
चैप्टर सारांश
  • http.HandleFunc एक URL pattern से मेल खाते requests handle करने के लिए एक function register करता है।
  • एक handler function एक http.ResponseWriter (response लिखने के लिए) और एक *http.Request (incoming request describe करते हुए) प्राप्त करता है।
  • http.ListenAndServe server शुरू करता है, किसी दिए address पर connections के लिए block और listen करते हुए।
  • http.NewRequest plus सीधे किसी handler को call करना बिना असली network listener के handler logic demonstrate करने का एक सरल तरीका है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.