Advertisement

The Previous Blog we talked about How the Golang HTTP Server is created using the Golang TCP Server using the Go Net Package. In this blog, we will take a look at Golang ResponseWriter and Request in net/http package Handler Interface.

But we don’t have to make that much effort just to create a server in Golang. The Go Developers have already created the net/http package that we can use to create servers.

The Go Doc has a fantastic Documentation, Must Read the Net/Http Package. But The Documentation is very large and it contains all the functions, so the beginners often do not understand from where to start learning. Follow this blog to learn the Golang Handler from the net/http package.

What is Web Server?

Golang HTTP Server - Request Response
Source – Divyanshu Shekhar

In simple terms, Web Server is a combination of Software and Hardware both working together in order to handle the requests coming from the browser and provide a response based on the incoming requests.

The above image depicts the Request-Response Architecture of the Web Server.

Golang Handler Interface

type Handler interface {     
          ServeHTTP(ResponseWriter, *Request) 
}

The Handler interface in Golang net/http package wraps serveHTTP Function that takes Response and Pointer to Request.

Golang HTTP Listen And Serve

func ListenAndServe(port string, handler Handler) error

The ListenAndServer function from the net/http package takes port as a string and the handler and returns an error if any.

ListenAndServe Function implements the TCP under the hood.

Golang ResponseWriter

type ResponseWriter interface {
    Header() Header
    Write([]byte) (int, error)
    WriteHeader(statusCode int)
}

 

The Golang net/http Handler interface has serveHTTP method that takes the Response Writer interface as input and this allows the Golang HTTP Server to construct HTTP Response.

package main

import (
	"fmt"
	"net/http"
)

type webServer int

func (web webServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Golang HTTP Server")
}

func main() {

	var web webServer
	http.ListenAndServe(":8080", web)

}

On running the Program and opening path localhost:8080

Golang ResponseWriter

The Above Program has an int-type webServer, and we attach the server HTTP method to it and thus the int-type webServer also starts behaving like a Handler and we can pass it to the ListenAndServe Function that takes an address and the Handler to Handle.

Golang ResponseWriter Set Headers

w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Divyanshu-Shekhar","DS")

Golang ResponseWriter Header

Golang Request Struct

type Request struct {
    
    Method string
    URL *url.URL
    //	Header = map[string][]string{
    //		"Accept-Encoding": {"gzip, deflate"},
    //		"Accept-Language": {"en-us"},
    //		"Foo": {"Bar", "two"},
    //	}
    Header Header
    Body io.ReadCloser
    ContentLength int64
    Host string
    Form url.Values
    PostForm url.Values

}

The Request in Golang net/http package is a struct that contains many fields that makes a complete Request.

Request Struct includes fields like Method, URL, Header, Body, Content-Length, Form Data, etc.

Golang Request Body

{{if .}}

Request Data


Method {{.Method}}

{{if .Host}}

Host {{.Host}}

{{end}} {{end}} {{if .ContentLength}}

ContentLength {{.ContentLength}}

{{end}} {{if .Submission}}

Form Submission

{{range $key, $value := .Submission}}
  • {{$key}} {{$value}}
{{end}} {{end}}

The Above HTML code is just the template version that is filled by the Go Program.

package main

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

var tmp *template.Template

type webServer int

func init() {
	tmp = template.Must(tmp.ParseFiles("index.html"))
}

func (web webServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	err := req.ParseForm()
	if err != nil {
		log.Fatalln(err)
	}
	type reqData struct {
		Method        string
		URL           *url.URL
		Submission    map[string][]string
		Header        http.Header
		Host          string
		ContentLength int64
	}
	data := reqData{
		req.Method,
		req.URL,
		req.Form,
		req.Header,
		req.Host,
		req.ContentLength,
	}
	tmp.ExecuteTemplate(w, "index.html", data)
}

func main() {

	var web webServer
	http.ListenAndServe(":8080", web)

}

Handler Request Parameters

Golang HTTP Server Post Example

package main

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

var tmp *template.Template

type webServer int

func init() {
	tmp = template.Must(tmp.ParseFiles("index.html"))
}

func (web webServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		log.Fatalln(err)
	}
	tmp.ExecuteTemplate(w, "index.html", r.Form)
}

func main() {

	var web webServer
	http.ListenAndServe(":8080", web)

}

Handler Post Form Example

Hope you like it!

Also, read Why Golang is called the future of Server-side language?

About Author
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top