Create file server with Golang - Read part

Server

Language :

Hi, I’m Lovefield.

Recently, I encountered several problems with Node.js while managing the file server. After much thought, I decided to move on to Golang and quickly started working on it. Golang was more satisfying than I thought, and This article is the method I used.

First, if you want to use Golang. You download it. Download Golang on this site https://go.dev/dl/.And you can check install complete with this command :

shell

go version

If you identified the version. Now make basically code in the read file.1. Create a


1. Create a "go.mod" file.

text

module main

go 1.20

require ()

This file has project information for using Golang, like package.json in Node.js.module main is specifies the package to run like npm run.

2. Create an "index.go" file.

text

package main

import ()

func main(){
  …
}

This is the default structure of Golang. Create a main function using func. By registering the main function name in package, this Golang recognizes that there is a main package. In the "go.mod" file, the name declared in the module part becomes the package name. In other words, if you run it using the command go run., read the module part declared in "go.mod" to explore the package that needs to be executed. "index.go" registered a function called main in the package, so the function will be executed.

So, we're actually going to read the files on the server in Golang and put them in response. By default, the following modules were used: "net/http", "os", "github.com/gorilla/mux "

"net/http" and "os" are the primary modules and do not need to be installed separately. "github.com/gorilla/mux " is a module that needs to be installed separately, so the terminal uses the following command:

text

go get -u github.com/gorilla/mux

Once the installation is complete, register the module to be used.

text

import (
  “net/http”
  “os”
  “github.com/gorilla/mux”
)

If IDE has Golang related settings, used modules will be automatically loaded and unused modules will be automatically removed. Now create the main function.

text

func main(){
  r := mux.NewRouter() # mux 라우터

  r.HandleFunc("/file/{fileName}", func(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r) # URL 파라미터 값 추출
    fileBytes, err := os.ReadFile(“somePath”+vars[“fileName”]) # 파일 읽기

    if err != nil{ # 에러
      panic(err)
    }

    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/octet-stream")
    w.Write(fileBytes)  
  }).Methods("GET")


  http.ListenAndServe(":3000", r) # 서버 시작
}

The code above is very simple. You just get the file name in the URL and read the file and drop it off to the body. It was simpler than I thought to read the file to Golang. I've implemented more functions here. These technologies will be described in the next article. Thank you.

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.