본문 바로가기

GO

2) GO RESTAPI 만들기.

반응형

설정된 개발환경에서 main.go에 아래와 같이 간단한 rest api 를 만들어 봤다. 

 

package main

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

func main(){
	//fmt.Println("main test 입니다.")

	router := httprouter.New()
	router.GET("/hello", HelloAPI)

	log.Fatal(http.ListenAndServe(":8080", router))

}

func HelloAPI(rs http.ResponseWriter, r *http.Request, ps httprouter.Params){
	fmt.Fprintln(rs , "Hello GO!")
}

 

위 코드를 httprouter 라는 package가 import 되어 있지 않아 컴파일 에러가 발생하게된다. 

이를 해결하기 위해 go get 으로 httprouter 를 설치하고 package를 import 해야 한다. 

아래는 httprouter의 go get 실행 구문이다.

go get github.com/julienschmidt/httprouter

이를 실행하면 다시 아래와 같은 에러가 나올수 있다.

이것은 go get 으로 package를 다운로드 받느데 git를 사용하게 되는데 로컬에 git이 설치 되어있지 않기 떄문이다. 

이를 해결하기 위해 git를 다운받아 설치한다.

https://git-scm.com/download/

 

Git - Downloads

Downloads macOS Windows Linux/Unix Older releases are available and the Git source repository is on GitHub. GUI Clients Git comes with built-in GUI tools (git-gui, gitk), but there are several third-party tools for users looking for a platform-specific exp

git-scm.com

git을 설치가 완료 가 환경변수에 이 정상적으로 추가되면 아래와 같이 git 명령어를 사용할수 있게 된다.

이제 위의 소스코드에 package를 import하고 go run을 실행해 보자.

package main

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

func main(){
	//fmt.Println("main test 입니다.")

	router := httprouter.New()
	router.GET("/hello", HelloAPI)

	log.Fatal(http.ListenAndServe(":8080", router))

}

func HelloAPI(rs http.ResponseWriter, r *http.Request, ps httprouter.Params){
	fmt.Fprintln(rs , "Hello GO!")
}

 

 

위와 같이 8080 포트에 접속이 되고 정상적으로 request 에 대한 결과가 오는것을 확인 할 수 있다

 

이렇게 간단한 소스를 구현해 봤는데 이제 이 소스를 git 에 올려 보고 올린 git에 대해 circleci로 CI/CD를 구현해 보고 

 

docker 이미지로 만들어 쿠버네티스에 배포하는것까지 테스트해 보도록 하겠다.

'GO' 카테고리의 다른 글

5) AWS ECR에 docker images Push하기  (0) 2021.03.05
4) Go Dockerfile 만들기 ( go mod )  (0) 2021.02.20
3) GO Module 이란? GO Module 테스트  (0) 2021.02.17
1) GO 설치하기  (0) 2021.02.01