BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

GoLang Tutorial - Web App 3 (Adding "edit" capability)

GCP-ICON.png




Bookmark and Share





bogotobogo.com site search:






Adding EDIT feature

Continued from Web Application Part 2.

In this post, we'll be adding "EDIT" capability to the wiki pages we created in the previous tutorial.

So, let's create two new handlers: one named editHandler to display an 'edit page' form, and the other named saveHandler to save the data entered via the form:

func main() {
    http.HandleFunc("/view/", viewHandler)
    http.HandleFunc("/edit/", editHandler)
    http.HandleFunc("/save/", saveHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

The function editHandler loads the page (or, if it doesn't exist, create an empty Page struct), and displays an HTML form:

func editHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/edit/"):]
    p, err := loadPage(title)
    if err != nil {
        p = &Page{Title: title}
    }
    fmt.Fprintf(w, "<h1>Editing %s</h1>"+
        "<form action=\"/save/%s\" method=\"POST\">"+
        "<textarea name=\"body\">%s</textarea><br>"+
        "<input type=\"submit\" value=\"Save\">"+
        "</form>",
        p.Title, p.Title, p.Body)
}

Though this function will work fine, as we can see the hard-coded HTML looks ugly. So, let's use html/template package instead.






html/template package

The html/template package is part of the Go standard library. We can use it to keep the HTML in a separate file, allowing us to change the layout of our edit page without modifying the underlying Go code.

First, we must add html/template to the list of imports. We also won't be using fmt anymore, so we have to remove that.

import (
	"html/template"
	"io/ioutil"
	"net/http"
)

Let's create a template file containing the HTML form (edit.html):

<h1>Editing {{.Title}}</h1>

<form action="/save/{{.Title}}" method="POST">
<div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div>
<div><input type="submit" value="Save"></div>
</form>

So, we need to modify editHandler to use the template, instead of the hard-coded HTML:

func editHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/edit/"):]
    p, err := loadPage(title)
    if err != nil {
        p = &Page{Title: title}
    }
    t, _ := template.ParseFiles("edit.html")
    t.Execute(w, p)
}

The function template.ParseFiles will read the contents of edit.html and return a *template.Template.

The method t.Execute executes the template, writing the generated HTML to the http.ResponseWriter. The .Title and .Body dotted identifiers refer to p.Title and p.Body.

Template directives are enclosed in double curly braces. The printf "%s" .Body instruction is a function call that outputs .Body as a string instead of a stream of bytes, the same as a call to fmt.Printf.

The html/template package helps guarantee that only safe and correct-looking HTML is generated by template actions. For instance, it automatically escapes any greater than sign (>), replacing it with &gt;, to make sure user data does not corrupt the form HTML.


Since we're working with templates now, let's create a template for our viewHandler called view.html:

<h1>{{.Title}}</h1>

<p>[<a href="/edit/{{.Title}}">edit</a>]</p>

<div>{{printf "%s" .Body}}</div>

Modify viewHandler accordingly:

func viewHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/view/"):]
    p, _ := loadPage(title)
    t, _ := template.ParseFiles("view.html")
    t.Execute(w, p)
}

Notice that we've used almost exactly the same templating code in both handlers. Let's remove this duplication by moving the templating code to its own function:

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    t, _ := template.ParseFiles(tmpl + ".html")
    t.Execute(w, p)
}

And modify the handlers to use that function:

func viewHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/view/"):]
    p, _ := loadPage(title)
    renderTemplate(w, "view", p)
}

func editHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/edit/"):]
    p, err := loadPage(title)
    if err != nil {
        p = &Page{Title: title}
    }
    renderTemplate(w, "edit", p)
}

template-code-1.png template-code-2.png

This file is available: wiki-app-3.go


With view.text like this, while the web server running, a visit to http://localhost:8080/view/test should show a page titled "test" containing the words "Hello GoLang - I am using html/template package!":

Hello GoLang - I am using html/template package!

As we can see from the browser, we now have [Edit] menu.

page-with-Edit-menu.png

And "save" button as well:

page-with-Edit-menu-and-save-button.png.png

Well, we commented out the registration of our unimplemented save handler in main, the "save" button is not working yet. If we click the "save", we get:

404-page-not-found.png






Continues to Web Application Part 4 (Handling non-existent pages and saving pages).





Go Tutorial


  1. GoLang Tutorial - HelloWorld
  2. Calling code in an external package & go.mod / go.sum files
  3. Workspaces
  4. Workspaces II
  5. Visual Studio Code
  6. Data Types and Variables
  7. byte and rune
  8. Packages
  9. Functions
  10. Arrays and Slices
  11. A function taking and returning a slice
  12. Conditionals
  13. Loops
  14. Maps
  15. Range
  16. Pointers
  17. Closures and Anonymous Functions
  18. Structs and receiver methods
  19. Value or Pointer Receivers
  20. Interfaces
  21. Web Application Part 0 (Introduction)
  22. Web Application Part 1 (Basic)
  23. Web Application Part 2 (Using net/http)
  24. Web Application Part 3 (Adding "edit" capability)
  25. Web Application Part 4 (Handling non-existent pages and saving pages)
  26. Web Application Part 5 (Error handling and template caching)
  27. Web Application Part 6 (Validating the title with a regular expression)
  28. Web Application Part 7 (Function Literals and Closures)
  29. Building Docker image and deploying Go application to a Kubernetes cluster (minikube)
  30. Serverless Framework (Serverless Application Model-SAM)
  31. Serverless Web API with AWS Lambda
  32. Arrays vs Slices with an array left rotation sample
  33. Variadic Functions
  34. Goroutines
  35. Channels ("<-")
  36. Channels ("<-") with Select
  37. Channels ("<-") with worker pools
  38. Defer
  39. GoLang Panic and Recover
  40. String Formatting
  41. JSON
  42. SQLite
  43. Modules 0: Using External Go Modules from GitHub
  44. Modules 1 (Creating a new module)
  45. Modules 2 (Adding Dependencies)
  46. AWS SDK for Go (S3 listing)
  47. Linked List
  48. Binary Search Tree (BST) Part 1 (Tree/Node structs with insert and print functions)
  49. Go Application Authentication I (BasicAuth, Bearer-Token-Based Authentication)
  50. Go Application Authentication II (JWT Authentication)




Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Go Tutorial



HelloWorld

Calling code in an external package & go.mod / go.sum files

Workspaces

Workspaces II

Visual Studio Code

Data Types and Variables

byte and rune

Packages

Functions

Arrays and Slices

A function taking and returning a slice

Conditionals

Loops

Maps

Range

Pointers

Closures and Anonymous Functions

Structs and receiver methods

Value or Pointer Receivers

Interfaces

Web Application Part 0 (Introduction)

Web Application Part 1 (Basic)

Web Application Part 2 (Using net/http)

Web Application Part 3 (Adding "edit" capability)

Web Application Part 4 (Handling non-existent pages and saving pages)

Web Application Part 5 (Error handling and template caching)

Web Application Part 6 (Validating the title with a regular expression)

Web Application Part 7 (Function Literals and Closures)

Building Docker image and deploying Go application to a Kubernetes cluster (minikube)

Serverless Framework (Serverless Application Model-SAM)

Serverless Web API with AWS Lambda

Arrays vs Slices with an array left rotation sample

Variadic Functions

Goroutines

Channels ("<-")

Channels ("<-") with Select

Channels ("<-") with worker pools

Defer

GoLang Panic and Recover

String Formatting

JSON

SQLite

Modules 0: Using External Go Modules from GitHub

Modules 1 (Creating a new module)

Modules 2 (Adding Dependencies)

AWS SDK for Go (S3 listing)

Linked List

Binary Search Tree (BST) Part 1 (Tree/Node structs with insert and print functions)

Go Application Authentication I (BasicAuth, Bearer-Token-Based Authentication)

Go Application Authentication II (JWT Authentication)


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong








C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master