DEVSIGHT.kr

Go 언어의 REST API 심플 예제이다.1. 동영상 강좌로 TutorialEdge, Golang Development를 추천한다.

go 설치 후 환경변수 설정

GOPATH는 Go 언어에서 프로젝트를 생성하고 개발할 때 기본 작업 디렉터리로 사용한다.

아래처럼 'GoProjects' 폴더를 만들었다면 이 안에 'bin', 'pkg', 'src' 폴더를 만들고 다시 src 폴더에 프로젝트 폴더(예, hello)를 만들고 이 안에 'main.go' 파일을 만든다.

이제 'go run'을 실행할 경우 화면에 결과를 보여주며(temp폴더에 임시빌드), 'go build' 하면 프로젝트 폴더명(hello)으로 실행 파일(hello.exe)을 만들어 준다.

rem C:\GoProjects\bin
rem C:\GoProjects\pkg
rem C:\GoProjects\src\hello\main.go

Temp 디렉터리는 'go run'을 실행할 때 백신에 따라 'access denied'가 메시지가 나오는 데 백신에 예외처리를 해주어 해결한다.

main.go example
package main

import (
    "encoding/json"
    "log"
    "math/rand"
    "net/http"
    "strconv"

    "github.com/gorilla/mux"
)

// Book Model
type Book struct {
    ID     string    `json:"id"`
    Isbn   string    `json:"isbn"`
    Title  string    `json:"title"`
    Author *[]Author `json:"author"`
}

// Author Model
type Author struct {
    Name    string `json:"name"`
    Address string `json:"address"`
}

var books []Book

func setBook(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var book Book
    _ = json.NewDecoder(r.Body).Decode(&book)
    book.ID = strconv.Itoa(rand.Intn(100000000))
    books = append(books, book)
    json.NewEncoder(w).Encode(book)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/books", setBook).Methods("POST")
    log.Fatal(http.ListenAndServe(":8000", r))
}

[[more]]

go get -u github.com/gorilla/mux 명령어로 mux router를 설치한다. 아래는 Concurrency2.

Concurrency
package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "sync"
)

var wg sync.WaitGroup
var mut sync.Mutex

func sendRequest(url string) {
    defer wg.Done()
    res, err := http.Get(url)
    if err != nil {
        panic(err)
    }

    mut.Lock()
    defer mut.Unlock()
    fmt.Printf("[%d] %s\n", res.StatusCode, url)
}

func main() {
    if len(os.Args) < 2 {
        log.Fatalln("usage: go run main.go <url 1>...<url n>")
    }

    for _, url := range os.Args[1:] {
        go sendRequest("https://" + url)
        wg.Add(1)
    }
    wg.Wait()
}
참고자료(study)
Reference
  1. Traversy Media, Golang REST API With Mux
  2. Rohit Awate, Concurrency in Golang
Ξ 2020.10.01

'RustㆍZigㆍGo' 카테고리의 다른 글

Rust, 한글 2byte HEX En/Decoding  (0) 2026.05.05
Rust, Concurrency and Channels  (0) 2026.05.05
Rust, Global static objects  (0) 2026.05.05
Objects and behavior, Rust vs. C#  (0) 2026.05.05
Rust WebAPI using ACTIX  (0) 2026.05.05