Creating a Basic Web App
Pulling from our fileserver program that we implemented last chapter, we will
implement a Markdown generator using the
package.
For starters, we will need a basic HTML form for the markdown input:
The “/markdown” route
The program to handle the ‘/markdown’ route and serve the public index.html
file looks like this:
Let’s break it down into smaller pieces to get a better idea of what is going
on.
Our GenerateMarkdown function implements the standard http.HandlerFunc
interface and renders HTML from a form field containing
markdown-formatted text. In this case, the content is retrieved
with r.FormValue("body")
. It is very common to get input from thehttp.Request
object that the http.HandlerFunc
receives as an argument.
Some other examples of input are the r.Header
, , and r.URL
members.
We finalize the request by writing it out to our http.ResponseWriter
. Notice
that we didn’t explicitly send a response code. If we write out to the response
without a code, the net/http
package will assume that the response is a 200
OK
. This means that if something did happen to go wrong, we should set the
response code via the rw.WriteHeader()
method.
And that is all you need to be able to generate markdown as a service in Go. It
is a surprisingly small amount of code for the amount of heavy lifting it does.
In the next chapter we will learn how to deploy this application to the web
using Heroku.