Check out a free preview of the full Basics of Go course

The "Building a Local HTTP Server" Lesson is part of the full, Basics of Go course featured in this preview video. Here's what you'd learn in this lesson:

Maximiliano provides an overview of options for utilizing Go in web development, such as WebAssembly, transpiling to JavaScript, web servers, and web services. Additionally, a step-by-step guide on setting up a basic local HTTP server is included in this segment.

Preview
Close

Transcript from the "Building a Local HTTP Server" Lesson

[00:00:00]
>> So it's time now to go back to the idea of using Go for web development. So we've covered the fundamentals, and we have been using the web only to bring data and just render that data in the console. So just as a reminder, if you're a web developer, with Go, you can target web assembly.

[00:00:20]
So in this case, everything that we have seen so far can be actually exposed to JavaScript. So then you compile the module, and then JavaScript can actually execute the function from your package. And there is a type conversion that needs to be done between types in Go and types in JavaScript, but that's kind of the idea.

[00:00:42]
You can transfer it to JavaScript, I'm not sure why you wanna do that, but anyway, it's one option. In that case, you can actually access the DOM directly with the document query selector, but directly in Go. I don't know any companies actually using that thing. You can create a web server so you can serve your files as if it's Node.js, or Express.js, or even Apache, IIS, Engine X, and so on.

[00:01:09]
In this case, you can use it for static serving your files, or you can also create RESTful APIs or microservices. We will be focusing right now in the last two, so we are going to create a new project that we have a mix of both. So we are going to serve a website, we are going to see first how to serve it statically, then how we can do some kind of server-side render.

[00:01:32]
And mix data with HTML, see how we can do that, and then we will create a very simple web service with Vanilla Go. Because there are also frameworks and libraries that you can sit on top of Go to help you creating a more complex solution, but we will stay with the standard libraries.

[00:01:54]
So I'm going to go back to VS Code, and we are going to create the last project of this course. So now you're experts in doing this thing. You go create a folder. We are going to call this folder Frontend Masters Museum. We're going to create a museum, okay?

[00:02:17]
So I can call it Frontend Master Museum, like FEMM, double M or any name will work. So we'll serve the website of a museum that has the name Frontend Masters. We know the steps, so we do go mod init. We call it frontendmasters.com/go/museum, for example. And then we start with always the same thing, main.go, package main, and a function main, our entry point, the same as usual.

[00:03:03]
So now the only difference is that we are not going to work with the console. I mean, the console will always be there, but we will be focusing into delivering files and content to a web client, a browser. So for that, we're also going to use the HTTP package.

[00:03:21]
And the HTTP package has a couple of functions like exported functions. And the one I'm going to use is called ListenAndserve, ListenAndserve. It receives first an address, so the address that you want, this is going to open a port in your operating system for incoming connections over TCP.

[00:03:47]
Typically, you use your IP address or your domain colon and the port, or you can just use colon and a port, any port will work, any number, a valid port number, by the way. In this case, if you use that, you don't need to specify your host or your IP address because it's going to open that port on any network connection that you have in your computer.

[00:04:12]
And the second argument, it's called a handler that we're going to start by saying nil. ListenAndServe will actually return a possible error option, error value, that's the right word. So if for some reason, I don't know, for example, the port is already open, or in use, or it's not the port that you can actually open because there are some ports reserved for the OS.

[00:04:39]
In that case, you will go here and we can just print line, or fmt.Println The server couldn't, or we couldn't open the server, or Error while opening the server. So now if I run this, that looks pretty empty, but anyway, if I run this, go run., nothing happens, or it seems that nothing is happening.

[00:05:10]
So it's not returning control to the console. So what's going on here? We have a server, okay? Thank you for coming, see you next time. So the server is there, it's listening in port 3333. Do we have something? No, are we serving something? No, but the server is there.

[00:05:29]
And actually, the thread is there waiting until the server ends. When is the server ending? Never. So actually, if you wanna close it, you need to manually go to the console and press Ctrl+C. You need to interrupt the server. By default, servers are there up and running always.

[00:05:55]
That's because that's a server, right? So actually what we need to do is do something else with that, but just with that, we do have a server. So you can see, it's actually pretty simple. So what else we can do? Actually, we can start talking to the http.

[00:06:10]
And I'm going to refactor this a little bit. There are a couple of functions that start with Handle. So we can handle with a type or with a function. What is that? Give me a sec. Let's start with HandleFunc. We define a pattern, what's the pattern? A pattern is actually, for now, let's say the URL.

[00:06:37]
But this is a routing system. It's using a multiplexer that is making routes automatically. We have that without a library. So in this case, we can say that for the URL/, or for the URL /hello, doesn't matter, I'm going to pass a function. In Go, you can pass functions as arguments.

[00:07:02]
We haven't done that so far. And also, you can create literal functions. We did that in the previous example. So I can create a handle if I want to. Do you see the signature there? So it's always the same. It's not extremely complicated. But anyway, you have first something known as a response writer that we typically call it w.

[00:07:26]
It's an http ResponseWriter. By the way, I need to add func here. Let me get some space. And also, we also have the response, sorry, the request. We also have the request. That is a pointer to http.Request. That's the signature from an http handler, so I'm not defining that.

[00:07:54]
You can do this if you want. If you like it, let's take that. It should go the same line. Okay, like that. And actually, the idea is that when you are going to that URL, so localhost, your port /hello, it will be handled by this function. That's the idea.

[00:08:17]
So how? Well, we have that request and this is kind of writer to the response. If the order seems reversed, right, it's not a natural order typically within think request first and response after, but anyway. So, for example, on the writer, we can actually write. We need to write not strings, but array that slice of bytes.

[00:08:43]
That point you say, that's complicated, but just remember that we can quickly call the converter. There is a function with the name of the type even with the square brackets, where we can say, Hello from a Go program. So if I try this, of going to the console now where nothing happens, I will open a Chrome window, a new window, and make it smaller.

[00:09:21]
So we can actually do something like this. I can try localhost 3333. By default, if I'm going to the root, we get a 404. So this default multiplexer that we have, that server, it's smart enough that if there is no handle for a URL that I'm trying, it will return a 404, page not found.

[00:09:47]
We have that for free. And if I try /hello, we see Hello from a Go program. Pretty simple, simple and fast as you can see.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now