Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

A Micro Project report on

BUILDING A SIMPLE SERVER IN GO PROGRAMMING


Submitted to the CMR Institute of Technology in partial fulfilment of the requirement
for the award of the Laboratory of
GO PROGRAMMING LAB
Of
IV B.Tech I Semester
In
Computer Science and Engineering (Data Science)
Submitted by
L. Katyaeni (20R01A67F5)
L.Rupesh Reddy (20R01A67F6)
M. Sujith (20R01A67F8)
M. Yukta Shreya (20R01A67F9)
M. Harshith (20R01A67G0)

Under the Guidance Of


Ms. YamunaDevi
(Assistant Professor, CSE(Data Science) Dept)

CMR INSTITUTE OF TECHNOLOGY


(UGC AUTONOMOUS)
(Approved by AICTE,Affiliated to JNTU,Kukatpally,Hyderabad)
Kandlakoya,Medchal Road,Hyderabad
2023-2024

CMR Institute of Technology


(UGC AUTONOMOUS)
(Approved by AICTE, Affiliated to JNTU, Kukatpally, Hyderabad) Kandlakoya,
Medchal Road, Hyderabad.
CERTIFICATE
This is to certify that a Micro Project entitled with:

“PROCESS/THREAD SYNCHRONISATION ” is being

Submitted By

L. Katyaeni (20R01A67F5)

L.Rupesh Reddy (20R01A67F6)

M. Sujith (20R01A67F8)

M. Yukta Shreya (20R01A67F9)

M. Harshith (20R01A67G0)

In partial fulfillment of the requirement for award of the Go Programming Laboratory of IV


year B.Tech I Semester in CSE(DS) to the CMRIT, Hyderabad is a record of a bonafide work
carried out under our guidance and supervision.

Signature of Faculty Signature of HOD


Ms.Yamuna Devi Dr.G.Bala Krishna
(Assistant Professor)
ACKNOWLEDGEMENT

We are extremely grateful to Dr. M. Janga Reddy, Director, Dr. B. Satyanarayana,


Principal and Dr.G.Bala Krishna, Head of Department, Dept of Computer Science and
Engineering(Data Science), CMR Institute of Technology for their inspiration and valuable
guidance during entire duration.

We are extremely thankful to our Go Programming Lab faculty in-charge Ms.Yamuna


Devi, Dept of Computer Science and Engineering, CMR Institute of Technology for his
constant guidance, encouragement and moral support throughout the project.

We express our thanks to all staff members and friends for all the help and
coordination extended in bringing out this Project successfully in time.

Finally, we are very much thankful to our parents and relatives who guided directly or
indirectly for successful completion of the project.

L.Katyaeni (20R01A67F5)

L.Rupesh Reddy (20R01A67F6)

L.Rupesh Reddy (20R01A67F8)

M.Yukta Shreya (20R01A67F9)

M.Harshith (20R01A67G0)
CONTENTS

PARTICULARS

1.Introduction

2. Project components

3. Installing Dependencies

4. Implementation Steps

5. Creating and converting Text to PDF file

6. Conclusion

7.References
ABSTRACT
Go is a procedural programming language. It was developed in 2007 by Robert
Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an
open-source programming language. Programs are assembled by using packages,
for efficient management of dependencies. This language also supports an
environment adopting patterns alike to dynamic languages.
Go is a statically typed, concurrent, and garbage-collected programming language
created at Google in 2009. It is designed to be simple, efficient, and easy to learn,
making it a popular choice for building scalable network services, web
applications, and command-line tools.
Go is known for its support for concurrency, which is the ability to run multiple
tasks simultaneously. Concurrency is achieved in Go through the use of
Goroutines and Channels, which allow you to write code that can run multiple
operations at the same time. This makes Go an ideal choice for building high-
performance and scalable network services, as well as for solving complex
computational problems.
Another important feature of Go is its garbage collection, which automatically
manages memory for you. This eliminates the need for manual memory
management, reducing the likelihood of memory leaks and other bugs that can
arise from manual memory management.

Here are some key features of Go:

1. Simplicity: Go is designed to be easy to learn and use. Its syntax is


simple and straightforward, making it a good choice for beginners and
experienced programmers alike.
2. Concurrency: Go has built-in support for concurrency, allowing
developers to write efficient and scalable code for multicore and
distributed systems.
3. Garbage collection: Go has automatic memory management, which
frees developers from having to worry about memory allocation and
deallocation.
4. Fast compile times: Go has a fast compiler, which makes it easy to
iterate quickly during development.
5. Cross-platform support: Go can be compiled to run on many different
platforms, including Windows, Linux, and macOS.
6. Strong typing: Go is a statically typed language, which helps catch
errors at compile time rather than at runtime.
7. Go has a large and growing community of developers and is used by
many well-known companies.

Creating A Simple Web Server with Golang


Web servers are always a really cool and relatively simple project to get up and
running when trying to learn a new language. In Go, this is no different, and
building a web server using the net/http.

The package is an excellent way to come to grips with some of the basics.

Here, we’ll be focusing on creating a very simple web server using the net/http
package. If you’ve ever used something like Node’s Express JS or Python’s
Tornado, then you should hopefully see some similarities to how things are
handled.

We’ll first focus on building a simple server that can serve some really simple
content back to a client making requests to our server. Once we have achieved
this, we’ll then look at how we can serve static files before finally moving on to
how we can serve these files using HTTP over TLS or https for short.

PREREQUISITES

• Go version 1.16 or greater installed. To set this up, follow the How To
Install Go tutorial for your operating system.
• Ability to use curl to make web requests. To read up on curl, check out How
To Download Files with cURL.
• Familiarity with using JSON in Go, which can be found in the How To Use
JSON in Go tutorial.
• Experience with Go’s context package, which can be attained in the tutorial,
How To Use Contexts in Go.
• Experience running goroutines and reading channels, which can be gained
from the tutorial, How To Run Multiple Functions Concurrently in Go.
• Familiarity with how HTTP requests are composed and sent
(recommended).
SETTING UP THE PROJECT

In Go, most of the HTTP functionality is provided by the net/http package in the
standard library, while the rest of the network communication is provided by the
net package. The net/http package not only includes the ability to make HTTP
requests, but also provides an HTTP server you can use to handle those requests.

In this section, you will create a program that uses the http.ListenAndServe
function to start an HTTP server that responds to the request paths / and /hello.
Then, you will expand that program to run multiple HTTP servers in the same
program.

Before you write any code, though, you’ll need to get your program’s directory
created. Many developers keep their projects in a directory to keep them
organized. In this tutorial, you’ll use a directory named projects.

First, make the projects directory. Next, make the directory for your project and
navigate to that directory. In this case, use the directory httpserver.

LISTENING TO REQUESTS AND RESPONDING

Now that you have your program’s directory created and you’re in the http server
directory, you can start implementing your HTTP server.

A Go HTTP server includes two major components: the server that listens for
requests coming from HTTP clients and one or more request handlers that will
respond to those requests. In this section, you’ll start by using the function
http.HandleFunc to tell the server which function to call to handle a request to the
server. Then, you’ll use the http.ListenAndServe function to start the server and
tell it to listen for new HTTP requests and then serve them using the handler
functions you set up.

In the main function, you have two calls to the http.HandleFunc function. Each call to
the function sets up a handler function for a specific request path in the default server
multiplexer. The server multiplexer is an http.Handler that is able to look at a request
path and call a given handler function associated with that path. So, in your program,
you’re telling the default server multiplexer to call the getRoot function when someone
requests the / path and the getHello function when someone requests
the /hello path.

Once the handlers are set up, you call the http.ListenAndServe function, which tells
the global HTTP server to listen for incoming requests on a specific port with an
optional http.Handler. In your program, you tell the server to listen on ":3333". By
not specifying an IP address before the colon, the server will listen on every IP address
associated with your computer, and it will listen on port 3333. A network port, such
as 3333 here, is a way for one computer to have many programs communicating with
each other at the same time. Each program uses its own port, so when a client
connects to a specific port the computer knows which program to send it to. If you
wanted to only allow connections to localhost, the hostname for IP
address 127.0.0.1, you could instead say 127.0.0.1:3333.

Your http.ListenAndServe function also passesa nil value for the http.Handler
parameter. This tells the ListenAndServe function that you want to use the default
server multiplexer and not the one you’ve set up.

The ListenAndServe is a blocking call, which means your program won’t continue
running until after ListenAndServe finishes running. However, ListenAndServe won’t
finish running until your program finishes running or the HTTP server is told to shut
down. Even though ListenAndServe is blocking and your program doesn’t include a
way to shut down the server, it’s still important to include error handling because there
are a few ways calling ListenAndServe can fail. So, add error handling to
your ListenAndServe in the main function.
Source code:
package main

import (

"context"

"errors"

"fmt"

"io"

"net"

"net/http"

const keyServerAddr = "serverAddr"

func getRoot(w http.ResponseWriter, r *http.Request) {

second := r.URL.Query().Get("second")

body, err := ioutil.ReadAll(r.Body)

if err != nil {

fmt.Printf("could not read body: %s\n", err)

fmt.Printf("%s: got / request. first(%t)=%s, second(%t)=%s, body:\n%s\n",

ctx.Value(keyServerAddr),

hasFirst, first,

hasSecond, second,

body)

io.WriteString(w, "This is my website!\n")


}

func getHello(w http.ResponseWriter, r *http.Request) {

ctx := r.Context()

fmt.Printf("%s: got /hello request\n", ctx.Value(keyServerAddr))

myName := r.PostFormValue("myName")

if myName == "" {

w.Header().Set("x-missing-field", "myName")

w.WriteHeader(http.StatusBadRequest)

return

io.WriteString(w, fmt.Sprintf("Hello, %s!\n", myName))

func main() {

mux.HandleFunc("/hello", getHello)

ctx := context.Background()

server := &http.Server{

Addr: ":3333",

Handler: mux,

BaseContext: func(l net.Listener) context.Context {

ctx = context.WithValue(ctx, keyServerAddr, l.Addr().String())

return ctx

},
}

err := server.ListenAndServe()

if errors.Is(err, http.ErrServerClosed) {

fmt.Printf("server closed\n")

} else if err != nil {

fmt.Printf("error listening for server: %s\n", err)

To run your server use the below commands:

$ go run main.go //to run the code.

CONTROL+C // to stop the server

OUTPUT:

This is my website!

Hello, HTTP!

[::]:3333: got /hello request

CONCLUSION:

In this tutorial, you created a new Go HTTP server using the net/http package in
Go’s standard library. You then updated your program to use a specific server
multiplexer and multiple http.Server instances. You also updated your server to
read user input via query string values, the request body, and form data. Finally, you
updated your server to return form validation information to the client using a custom
HTTP header and a “Bad Request” status code.

One good thing about the Go HTTP ecosystem is that many frameworks are designed
to integrate neatly into Go’s net/http package instead of reinventing a lot of the code
that already exists. The github.com/go-chi/chi project is a good example of this. The
server multiplexer built into Go is a good way to get started with an HTTP server, but
it lacks a lot of advanced functionality a larger web server may need. Projects such
as chi are able to implement the http.Handler interface in the Go standard library
to fit right into the standard http.Server without needing to rewrite the server portion
of the code. This allows them to focus on creating middleware and other tooling to
enhance what’s available instead of working on the basic functionality.

REFERENCES:
For the "Text to PDF Converter in Go" micro project, you can refer to the following
resources and documentation to aid in your development:

1. Go Official Website: The official Go website is a comprehensive resource for all


things.

Go, including installation instructions, tutorials, and the Go standard library


documentation.

Website: https://golang.org/

2. Go Flag Package: For creating the command-line interface, refer to the official
documentation of the "flag" package in Go.

Documentation: https://pkg.go.dev/flag

3. GitHub Repository for "github.com/jung-kurt/gofpdf": This is the library you will use
for PDF generation in your Go project. You can find documentation, examples, and
usage details in the repository.

Repository: https://github.com/jung-kurt/gofpdf
4. Go by Example: This website offers a variety of Go programming examples,
including file handling, command-line arguments, and error handling, which can be
very helpful for your project.

Website: https://gobyexample.com/

5. A Tour of Go: This is an interactive tutorial provided by the Go team, covering the
basics of the Go programming language, which can be a great starting point for
learning Go.

Website: https://tour.golang.org/welcome/1

6. Go Modules Documentation: If you're using Go Modules for dependency


management, the official Go Modules documentation provides details on how to
manage your project's dependencies.

Documentation: https://golang.org/ref/mod

You might also like