खोज…


टिप्पणियों

http.ServeMux एक मल्टीप्लेक्स प्रदान करता है जो HTTP अनुरोधों के लिए हैंडलर को बुलाता है।

मानक पुस्तकालय मल्टीप्लेक्सर के विकल्प में शामिल हैं:

कस्टम सर्वर और mux के साथ HTTP हैलो वर्ल्ड

package main

import (
    "log"
    "net/http"
)

func main() {

    // Create a mux for routing incoming requests
    m := http.NewServeMux()

    // All URLs will be handled by this function
    m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, world!"))
    })

    // Create a server listening on port 8000
    s := &http.Server{
        Addr:    ":8000",
        Handler: m,
    }

    // Continue to process new requests until an error occurs
    log.Fatal(s.ListenAndServe())
}

प्रक्रिया को रोकने के लिए Ctrl + C दबाएं

नमस्ते दुनिया

गोलंग में webservers लिखना शुरू करने का विशिष्ट तरीका मानक पुस्तकालय net/http मॉड्यूल का उपयोग करना है।

यहां इसके लिए एक ट्यूटोरियल भी है

निम्न कोड भी इसका उपयोग करता है। यहाँ HTTP सर्वर कार्यान्वयन सबसे सरल संभव है। यह किसी भी HTTP अनुरोध के लिए "Hello World" का जवाब देता है।

अपने कार्यक्षेत्र में एक server.go में निम्नलिखित कोड को सहेजें।

package main

import (
    "log"
    "net/http"
)

func main() {
    // All URLs will be handled by this function
    // http.HandleFunc uses the DefaultServeMux
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, world!"))
    })

    // Continue to process new requests until an error occurs
    log.Fatal(http.ListenAndServe(":8080", nil))
}

आप सर्वर का उपयोग करके चला सकते हैं:

$ go run server.go

या आप संकलित और चला सकते हैं।

$ go build server.go
$ ./server

सर्वर निर्दिष्ट पोर्ट ( :8080 ) को सुनेगा। आप किसी भी HTTP क्लाइंट के साथ इसका परीक्षण कर सकते हैं। यहाँ cURL साथ एक उदाहरण दिया गया है:

curl -i http://localhost:8080/
HTTP/1.1 200 OK
Date: Wed, 20 Jul 2016 18:04:46 GMT
Content-Length: 13
Content-Type: text/plain; charset=utf-8

Hello, world!

प्रक्रिया को रोकने के लिए Ctrl + C दबाएं

एक हैंडलर फ़ंक्शन का उपयोग करना

HandleFunc सर्वर mux (राउटर) में दिए गए पैटर्न के लिए हैंडलर फ़ंक्शन को पंजीकृत करता है।

आप एक अनाम फ़ंक्शन को परिभाषित कर सकते हैं, जैसा कि हमने मूल हैलो वर्ल्ड उदाहरण में देखा है:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, world!")
}

लेकिन हम एक HandlerFunc प्रकार भी पास कर सकते हैं। दूसरे शब्दों में, हम निम्नलिखित हस्ताक्षर का सम्मान करने वाले किसी भी कार्य को पारित कर सकते हैं:

func FunctionName(w http.ResponseWriter, req *http.Request)

हम पहले से परिभाषित HandlerFunc के संदर्भ में पिछले उदाहरण को फिर से लिख सकते हैं। यहां देखें पूरा उदाहरण:

package main

import (
    "fmt"
    "net/http"
)

// A HandlerFunc function
// Notice the signature of the function
func RootHandler(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Hello, world!")
}

func main() {
    // Here we pass the reference to the `RootHandler` handler function
    http.HandleFunc("/", RootHandler)
    panic(http.ListenAndServe(":8080", nil))
}

बेशक, आप विभिन्न रास्तों के लिए कई फ़ंक्शन हैंडलर को परिभाषित कर सकते हैं।

package main

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

func FooHandler(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Hello from foo!")
}

func BarHandler(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Hello from bar!")
}

func main() {
    http.HandleFunc("/foo", FooHandler)
    http.HandleFunc("/bar", BarHandler)

    log.Fatal(http.ListenAndServe(":8080", nil))
}

यहाँ आउटपुट का उपयोग कर cURL :

➜  ~ curl -i localhost:8080/foo
HTTP/1.1 200 OK
Date: Wed, 20 Jul 2016 18:23:08 GMT
Content-Length: 16
Content-Type: text/plain; charset=utf-8

Hello from foo!

➜  ~ curl -i localhost:8080/bar
HTTP/1.1 200 OK
Date: Wed, 20 Jul 2016 18:23:10 GMT
Content-Length: 16
Content-Type: text/plain; charset=utf-8

Hello from bar!

➜  ~ curl -i localhost:8080/
HTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Wed, 20 Jul 2016 18:23:13 GMT
Content-Length: 19

404 page not found

एक HTTPS सर्वर बनाएँ

एक प्रमाण पत्र बनाएं

HTTPS सर्वर को चलाने के लिए, एक प्रमाणपत्र आवश्यक है। के साथ एक स्व-हस्ताक्षरित प्रमाणपत्र जनरेट कर रहा है openssl इस कमांड को क्रियान्वित किया जाता है:

openssl req -x509 -newkey rsa:4096 -sha256 -nodes -keyout key.pem -out cert.pem -subj "/CN=example.com" -days 3650`

पैरामीटर हैं:

  • req प्रमाणपत्र अनुरोध उपकरण का उपयोग करें
  • x509 एक स्व-हस्ताक्षरित प्रमाण पत्र बनाता है
  • newkey rsa:4096 4096 बिट कुंजी लंबाई के साथ RSA एल्गोरिदम का उपयोग करके एक नई कुंजी और प्रमाणपत्र बनाता है
  • sha256 SHA256 हैशिंग एल्गोरिदम को मजबूर करता है जो प्रमुख ब्राउज़र सुरक्षित मानते हैं (वर्ष 2017 में)
  • nodes निजी कुंजी के लिए पासवर्ड सुरक्षा अक्षम करता है। इस पैरामीटर के बिना, आपके सर्वर को हर बार इसके शुरू होने पर आपसे पासवर्ड मांगना पड़ता था।
  • keyout उस फाइल को नाम देता है जहाँ कुंजी लिखना है
  • out नाम फ़ाइल जहां प्रमाण पत्र लिखने के
  • subj उस डोमेन नाम को परिभाषित करता है जिसके लिए यह प्रमाणपत्र मान्य है
  • days FOW कितने दिन करना चाहिए इस प्रमाणपत्र मान्य? 3650 लगभग हैं। 10 साल।

नोट: एक स्व-हस्ताक्षरित प्रमाण पत्र का उपयोग आंतरिक परियोजनाओं, डिबगिंग, परीक्षण, आदि के लिए किया जा सकता है। वहाँ से बाहर किसी भी ब्राउज़र का उल्लेख होगा, कि यह प्रमाण पत्र सुरक्षित नहीं है। इससे बचने के लिए, प्रमाणपत्र को एक प्रमाणीकरण प्राधिकारी द्वारा हस्ताक्षरित होना चाहिए। अधिकतर, यह मुफ्त में उपलब्ध नहीं है। एक अपवाद "लेट्स एनक्रिप्ट" आंदोलन है: https://letsencrypt.org

आवश्यक गो कोड

आप निम्न कोड वाले सर्वर के लिए TLS कॉन्फ़िगर कर सकते हैं। cert.pem और key.pem आपके एसएसएल प्रमाणपत्र और कुंजी हैं, जो उपरोक्त कमांड के साथ उत्पन्न होते हैं।

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, world!"))
    })

    log.Fatal(http.ListenAndServeTLS(":443","cert.pem","key.pem", nil))
}

टेम्प्लेट का उपयोग करके HTTP अनुरोध का जवाब देना

प्रतिक्रियाओं को गो में टेम्प्लेट का उपयोग करके http.ResponseWriter को लिखा जा सकता है। यदि आप डायनामिक पेज बनाना चाहते हैं तो यह एक उपयोगी टूल साबित होता है।

(यह जानने के लिए कि टेम्प्लेट गो में कैसे काम करते हैं, कृपया गो टेम्प्लेट प्रलेखन पृष्ठ पर जाएँ ।)

HTTP अनुरोध का जवाब देने के लिए html/template का उपयोग करने के लिए एक सरल उदाहरण के साथ जारी है:

package main

import(
    "html/template"
    "net/http"
    "log"
)

func main(){
    http.HandleFunc("/",WelcomeHandler)
    http.ListenAndServe(":8080",nil)
}

type User struct{
    Name string
    nationality string //unexported field.
}

func check(err error){
    if err != nil{
        log.Fatal(err)
    }
}

func WelcomeHandler(w http.ResponseWriter, r *http.Request){
    if r.Method == "GET"{
        t,err := template.ParseFiles("welcomeform.html")
        check(err)
        t.Execute(w,nil)
    }else{
        r.ParseForm()
        myUser := User{}
        myUser.Name = r.Form.Get("entered_name")
        myUser.nationality = r.Form.Get("entered_nationality")
        t, err := template.ParseFiles("welcomeresponse.html")
        check(err)
        t.Execute(w,myUser)
    }
}

कहाँ, की सामग्री

  1. welcomeform.html हैं:
<head>
    <title> Help us greet you </title>
</head>
<body>
    <form method="POST" action="/">
        Enter Name: <input type="text" name="entered_name">
        Enter Nationality: <input type="text" name="entered_nationality">
        <input type="submit" value="Greet me!">
    </form>
</body>
  1. welcomeresponse.html हैं:
<head>
    <title> Greetings, {{.Name}} </title>
</head>
<body>
    Greetings, {{.Name}}.<br>
    We know you are a {{.nationality}}!
</body>

ध्यान दें:

  1. सुनिश्चित करें कि .html फाइलें सही निर्देशिका में हैं।

  2. जब http://localhost:8080/ सर्वर शुरू करने के बाद दौरा किया जा सकता है।

  3. जैसा कि यह फॉर्म जमा करने के बाद देखा जा सकता है, संरचना के अस्पष्टीकृत राष्ट्रीयता क्षेत्र को टेम्पलेट पैकेज द्वारा पार्स नहीं किया जा सकता है, जैसा कि अपेक्षित था।

ServeMux का उपयोग करके सामग्री परोसना

एक साधारण स्थिर फ़ाइल सर्वर इस तरह दिखेगा:

package main

import (
    "net/http"
)

func main() {
    muxer := http.NewServeMux()
    fileServerCss := http.FileServer(http.Dir("src/css"))
    fileServerJs := http.FileServer(http.Dir("src/js"))
    fileServerHtml := http.FileServer(http.Dir("content"))
    muxer.Handle("/", fileServerHtml)
    muxer.Handle("/css", fileServerCss)
    muxer.Handle("/js", fileServerJs)
    http.ListenAndServe(":8080", muxer)
}

HTTP पद्धति को हैंडल करना, क्वेरी स्ट्रिंग्स तक पहुंचना और शरीर का अनुरोध करना

एपीआई विकसित करने, अनुरोध के HTTP विधि में अंतर करने, क्वेरी स्ट्रिंग मानों तक पहुंचने और अनुरोध निकाय तक पहुंचने के बीच कुछ सामान्य कार्यों के एक सरल उदाहरण यहां दिए गए हैं।

साधन

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type customHandler struct{}

// ServeHTTP implements the http.Handler interface in the net/http package
func (h customHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    // ParseForm will parse query string values and make r.Form available
    r.ParseForm()

    // r.Form is map of query string parameters
    // its' type is url.Values, which in turn is a map[string][]string
    queryMap := r.Form

    switch r.Method {
    case http.MethodGet:
        // Handle GET requests
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(fmt.Sprintf("Query string values: %s", queryMap)))
        return
    case http.MethodPost:
        // Handle POST requests
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            // Error occurred while parsing request body
            w.WriteHeader(http.StatusBadRequest)
            return
        }
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(fmt.Sprintf("Query string values: %s\nBody posted: %s", queryMap, body)))
        return
    }

    // Other HTTP methods (eg PUT, PATCH, etc) are not handled by the above
    // so inform the client with appropriate status code
    w.WriteHeader(http.StatusMethodNotAllowed)
}

func main() {
    // All URLs will be handled by this function
    // http.Handle, similarly to http.HandleFunc
    // uses the DefaultServeMux
    http.Handle("/", customHandler{})

    // Continue to process new requests until an error occurs
    log.Fatal(http.ListenAndServe(":8080", nil))
}

नमूना कर्ल उत्पादन:

$ curl -i 'localhost:8080?city=Seattle&state=WA' -H 'Content-Type: text/plain' -X GET
HTTP/1.1 200 OK
Date: Fri, 02 Sep 2016 16:36:24 GMT
Content-Length: 51
Content-Type: text/plain; charset=utf-8

Query string values: map[city:[Seattle] state:[WA]]%

$ curl -i 'localhost:8080?city=Seattle&state=WA' -H 'Content-Type: text/plain' -X POST -d "some post data"
HTTP/1.1 200 OK
Date: Fri, 02 Sep 2016 16:36:35 GMT
Content-Length: 79
Content-Type: text/plain; charset=utf-8

Query string values: map[city:[Seattle] state:[WA]]
Body posted: some post data%

$ curl -i 'localhost:8080?city=Seattle&state=WA' -H 'Content-Type: text/plain' -X PUT
HTTP/1.1 405 Method Not Allowed
Date: Fri, 02 Sep 2016 16:36:41 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow