A web app that just does Hello World with Go's net / http package

Awakening of Go

With low-layer knowledge, you'll be a self-sufficient engineer! I sent it to myself who enthusiastically learned C language but couldn't find any fun.

Persona

If you want to make a web application, I think Node and Rails are enough at present. For desktop apps, use Electron. Those who want to use Go or something like a terminal application or a system that uses OS functions (Docker and GitHub CLI, which are popular these days, are also made by Go, so if you can use it, you can play it).

Purpose of this article

To decide if you want to learn Go, let's create a simple web app (just display Hello World when you access it).

Development environment

I didn't know if I could trust Go, so I'll do it with Docker to keep the environment clean. If it is interesting, I would like to see the inside with a debugger, so I will build the environment locally.

The directory structure is as follows. Put the go file in the compileFile directory and build it.

compileFile (directory)
Dockerfile
docker-compose.yml
# Dockerfile
FROM golang:latest
RUN mkdir -p /go/src

docker-compose.yml


version: '3'
services:
  go:
    build: .
    ports:
      - "8080:8080"
    volumes:
      - ./compileFile:/go/src
    working_dir: /go/src

Go inside the container and check the go command. Note that you cannot connect 8080 ports unless you specify --service-ports. Make sure that you can port forward properly with docker ps.

$ docker-compose run --service-ports go /bin/bash
$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
af4f9c066ecd        golean_go           "/bin/bash"         7 seconds ago       Up 2 seconds        0.0.0.0:8080->8080/tcp   golean_go_run_a79a836040ab

For now, try typing go to see what commands you can use.

Go is a tool for managing Go source code.

Usage:

	go <command> [arguments]

The commands are:

	bug         start a bug report
	build       compile packages and dependencies
	clean       remove object files and cached files
	doc         show documentation for package or symbol
	env         print Go environment information
	fix         update packages to use new APIs
	fmt         gofmt (reformat) package sources
	generate    generate Go files by processing source
	get         add dependencies to current module and install them
	install     compile and install packages and dependencies
	list        list packages or modules
	mod         module maintenance
	run         compile and run Go program
	test        test packages
	tool        run specified go tool
	version     print Go version
	vet         report likely mistakes in packages

Use "go help <command>" for more information about a command.

Additional help topics:

	buildconstraint build constraints
	buildmode       build modes
	c               calling between Go and C
	cache           build and test caching
	environment     environment variables
	filetype        file types
	go.mod          the go.mod file
	gopath          GOPATH environment variable
	gopath-get      legacy GOPATH go get
	goproxy         module proxy protocol
	importpath      import path syntax
	modules         modules, module versions, and more
	module-get      module-aware go get
	module-auth     module authentication using go.sum
	module-private  module configuration for non-public modules
	packages        package lists and patterns
	testflag        testing flags
	testfunc        testing functions

Use "go help <topic>" for more information about that topic.

go build`` go run go fmt is likely to be used in the near future.

Project creation

I wanted to understand Go from a familiar web app. While looking at the sample code, write a program that displays Hello World on the browser.

server/main.go


package main

import "io"
import "net/http"

func mainHandler(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, `Hello World!!!`)
}

func main(){
	http.HandleFunc("/main", mainHandler)
	http.ListenAndServe(":8080", nil)
}

You can format it with one command, so build it after formatting! By the way, I'm angry if there is a line break position or an unused package, maybe the linter is also working at build time.

When I built it, an executable file with the directory name containing the go file was created.

$ go fmt
$ go build
$ ls
server main.go
$ ./server

When I visited http: // localhost: 8080 / main, I was able to confirm Hello World!

スクリーンショット 2020-10-13 1.23.10.png

By the way, if you want to run it on Mac, you can compile it for Mac below.

$ GOOS=darwin GOARCH=amd64 go build

net / http package

Let's start from an easy-to-understand place. It seems that you can set up a server with this. It seems that the first argument can specify the port and the second argument can select Handler, and in the case of nil, the default DefaultServeMux is used.

http.ListenAndServe(":8080", nil)

What is DefaultServeMux?

As you read through the documentation, you will find the following:

HandleFunc registers the handler function for the given pattern in the DefaultServeMux.
The documentation for ServeMux explains how patterns are matched.

It says that you can register a handler corresponding to the URL pattern in DefaultServerMux with HandleFunc. Think of it as something routing.

So, the following can be read as executing the processing of mainHandler after accessing / main.

http.HandleFunc("/main", mainHandler)

The io package knows what you're doing, so I'll leave it.

document Package http

Introduced to Local

You can easily enter with brew.

$ brew install go
$ go version
go version go1.15.3 darwin/amd64

Also include the REPL. It didn't work with gore v0.5.0, so I'm dropping the version.

#You can do this and install it, but you may not need it.
$ export GO111MODULE=on
$ go get github.com/motemen/gore/cmd/[email protected]
$ gore -version
gore 0.4.0 (rev: HEAD/go1.15.3)

If you install it by mistake, you can delete it below.

$ go clean -i github.com/motemen/gore/cmd/gore

By the way, with v0.5.0, the following error message appears.

gore: could not load 'fmt' package: err: exit status 1: stderr: build flag -mod=mod only valid when using modules

Now that the local environment is in place, all you have to do is play.

Summary

I want to use Go for web development! I don't feel like that, but at least I found it more fun than C! I want to make a terminal application or something. For the time being, in order to learn how to use Go, I thought I'd try to make it from a simple web application using a framework or something.

Recommended Posts

A web app that just does Hello World with Go's net / http package
Create a "Hello World" (HTTP) server with Tornado
Play like a web app with ipywidgets
Create a web app that can be easily visualized with Plotly Dash
Daemonize a Python web app with Supervisor
Create a simple web app with flask
A typed world that begins with Python
An article that just tries a little HTTP request with the curl command
Create a one-file hello world application with django
Hello World is a simple web server that follows WSGI (Web Server Gateway Interface) in Python.
I made a net news notification app with Python
Create a web server in Go language (net / http) (1)
Deploy a real-time web app with swampdragon x apache
Deploy a web app created with Streamlit to Heroku
hello world with ctypes
Hello, World with Docker
Hello world with flask
How to deploy a web app made with Flask to Heroku
Create a web application that recognizes numbers with a neural network
Hello World with Google App Engine (Java 8) + Servlet API 3.1 + Gradle
(Failure) Deploy a web app made with Flask on heroku
Tornado-Let's create a Web API that easily returns JSON with JSON
Create a web API that can deliver images with Django
Hello World with Google App Engine (Java 11) + Spring Boot + Gradle