0% found this document useful (0 votes)
17 views14 pages

Activity GO FINAL

The document contains 6 questions related to programming in Golang. The questions cover topics like form validation, creating a photo gallery, generating QR codes, concurrency, interfaces, and working with dates and timezones. Code snippets are provided as answers for each question.

Uploaded by

12thsuhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views14 pages

Activity GO FINAL

The document contains 6 questions related to programming in Golang. The questions cover topics like form validation, creating a photo gallery, generating QR codes, concurrency, interfaces, and working with dates and timezones. Code snippets are provided as answers for each question.

Uploaded by

12thsuhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Dr. D. Y.

Patil Unitech Society’s


Dr. D. Y. Patil Arts, Commerce and Science College
Akurdi Pune 411044
Academic Year : 2023-24

Name : Suhas Shankar Gondukupi


Class : T.Y.B.C.A. (sci.)
Roll No : 65
Subject : Programming in GO
Submitted to : Ms. Purva Morkhade

1
Q1. Write a program for Form validation in golang.
package main
import (
"html/template"
"log"
"net/http"
"github.com/bmizerany/pat"
)

func main() {
mux := pat.New()
mux.Get("/", http.HandlerFunc(home))
mux.Post("/", http.HandlerFunc(send))
mux.Get("/confirmation", http.HandlerFunc(confirmation))

log.Print("Listening...")
err := http.ListenAndServe(":3000", mux)
if err != nil {
log.Fatal(err)
}
}

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


render(w, "templates/home.html", nil)
}

2
func send(w http.ResponseWriter, r *http.Request) {
// Step 1: Validate form
// Step 2: Send message in an email
// Step 3: Redirect to confirmation page
}

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


render(w, "templates/confirmation.html", nil)
}

func render(w http.ResponseWriter, filename string, data interface{}) {


tmpl, err := template.ParseFiles(filename)
if err != nil {
log.Print(err)
http.Error(w, "Sorry, something went wrong",
http.StatusInternalServerError)
return
}

if err := tmpl.Execute(w, data); err != nil {


log.Print(err)
http.Error(w, "Sorry, something went wrong",
http.StatusInternalServerError)
}
}

3
Output :

4
Q2. Write a program to create a photo gallery in golang.
package main
import (
"crypto/sha1"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)

var tpl *template.Template

func init() {
tpl = template.Must(template.ParseGlob("templates/*"))
}
func main() {
http.HandleFunc("/", index)
http.Handle("/gallery/", http.StripPrefix("/gallery",
http.FileServer(http.Dir("./gallery"))))
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
5
func index(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodPost {
mf, fh, err := req.FormFile("nf")
if err != nil {
fmt.Println(err)
}
defer mf.Close()
// create sha for file name
ext := strings.Split(fh.Filename, ".")[1]
h := sha1.New()
io.Copy(h, mf)
fname := fmt.Sprintf("%x", h.Sum(nil)) + "." + ext
// create new file
wd, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
path := filepath.Join(wd, "gallery", fname)
nf, err := os.Create(path)
if err != nil {
fmt.Println(err)
}
defer nf.Close()
mf.Seek(0, 0)
io.Copy(nf, mf)

6
}
file, err := os.Open("gallery")
if err != nil {
log.Fatalf("failed opening directory: %s", err)
}
defer file.Close()
list, _ := file.Readdirnames(0) // 0 to read all files and folders
tpl.ExecuteTemplate(w, "index.gohtml", list)
}

Output :

7
Q3. Write a program to generate QR code in golang.

package main
import (
"fmt"
"image"
"image/png"
"os"

qrcode "github.com/skip2/go-qrcode"
)
func main() {
// Data to encode into QR code
data := "https://www.example.com"
qrCode, err := qrcode.Encode(data, qrcode.Medium, 256)
if err != nil {
fmt.Println("Error generating QR code:", err)
return
}
qrImage, err := qrCode.PNG(256)
if err != nil {
fmt.Println("Error creating QR code image:", err)
return
}

8
// Save QR code image to file
file, err := os.Create("qrcode.png")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()

// Write image data to file


_, err = file.Write(qrImage)
if err != nil {
fmt.Println("Error writing image data to file:", err)
return
}

fmt.Println("QR code generated and saved as qrcode.png")


}

Output :

9
Q 4. Write a program on Concurrency in golang

package main
import (
"fmt"
"time"
)
func main() {
go helloworld()
time.Sleep(3 * time.Second)
goodbye()
}
func helloworld() {
fmt.Println("Hello World!")
}

func goodbye() {
fmt.Println("Good Bye!")
}

10
Q5. Write a program on Interface with a common method.
package main

import "fmt"
type Shape interface {
Area() float64
}

type Rectangle struct {


Width float64
Height float64
}

func (r Rectangle) Area() float64 {


return r.Width * r.Height
}

type Circle struct {


Radius float64
}

func (c Circle) Area() float64 {


return 3.14 * c.Radius * c.Radius
}

11
func main() {
rectangle := Rectangle{Width: 5, Height: 3}
circle := Circle{Radius: 2}

printArea(rectangle)
printArea(circle)
}

func printArea(s Shape) {


fmt.Printf("Area of the shape: %.2f\n",s.Area())
}

Output :

12
Q6 ) Write a program to get the current date and timestamp in
local and other timezones.
package main
import (
"fmt"
"time"
)

func main() {
// Get current time in local timezone
localTime := time.Now()
fmt.Println("Local Time:", localTime.Format(time.RFC3339))

// Get current time in UTC timezone


utcTime := time.Now().UTC()
fmt.Println("UTC Time:", utcTime.Format(time.RFC3339))

// Specify another timezone (e.g., "America/New_York") and get


current time
otherTimezone := "America/New_York"
loc, err := time.LoadLocation(otherTimezone)
if err != nil {
fmt.Println("Error loading location:", err)
return
}

13
otherTime := time.Now().In(loc)
fmt.Printf("%s Time: %s\n", otherTimezone,
otherTime.Format(time.RFC3339))
}

Output

14

You might also like