File Upload Server in Golang

Haris Shafiq
3 min readJan 27, 2020

File Upload Server in Golang and Deployed through docker containers

Code and related files to this demo can be clone from following Git-repository https://github.com/Haris3243/file-upload-server.git

Prerequisites:

to get started with implementing file upload server backend we will use golang and after that we will deploy it with the help of docker containers

  1. Install Golang v.1.13.6
  2. Install Docker

1. Server Implementation

1.1 create your project and your main file i.e main.go

first define your package name and let it be main because each go project initiates its execution from main package that contains a main function which will be the entry point of execution

Fig 1.1 Hello World in Golang

Package fmt implements formatted I/O with functions analogous to C’s printf and scanf.

1.2. Now let’s implements function that will handle uploaded file which will take two arguments response and request, and store the file in data folder

Fig 1.2 FileHandler Function

1.3. Now implement the server function which will route the the incoming requests to uploadFile function that will eventually deals with the request and file

Fig 1.3 Server Function

from above function server will be listening to requests on http://localhost:8083/uploadFile

1.4. Now call this server function from main to initialize the server

Fig 1.4 start file upload server

1.5. Now, we have done with the implementation lets build the project with following command that will create an executable:

“ go build ./main.go”

2. Deployment through Docker Containers:

the above command creates an execute-able. we have to containerize that application so that it can be deployed to anywhere.

2.1 Create docker-file to make application’s image

Fig 2.1 Dockerfile

As we build our application to listen and server on 8083, so we have to Expose it to our container, Later On we will bind it with host port so that we can access it. Container’s port are directly not accessible from outer-world of container.

2.2 Now build the docker image from this docker-file

Fig 2.2 Building docker image from docker-file

2.3 Now run the container from this image through following command and check its status from docker ps command

Fig 2.3 Run a container

as you can see we have mapped host’s port 8080 and we can connect it by sending multipart/form-data request to http://localhost:8080/uploadFile

You can find all the source-code from https://github.com/Haris3243/file-upload-server

Thanks! for reading this article, hope that it will help you if you are new-bee to implement a server and its very simple in golang.

--

--