Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- Elk
- gin
- topic
- Message
- 쿠버네티스
- docker
- Kafka
- Produce
- create topic
- gortsplib
- ElasticSearch
- Kafka Connect
- eck
- broker
- http
- minikube
- gorm
- tls disable
- Kubernetes
- Golang
- kafka broker
- k8s
- Helm
- Consumer
- go test
- loadbalance
- kibana
- go
- kafka-connect
- consumer group
Archives
- Today
- Total
개발자의 개발괴발
gin으로 web service 시작하기 본문
반응형
go에 많은 web framework가 있지만 나는 gin을 선택했다.
장점, 단점을 읽어봤지만 나에게 중요한 것은 쉽고 빠르게 만들 수 있는 것이기 때문이다.
gin 시작하기
gin 시작하기는 매우 쉽다.
vscode에서 새로운 폴더를 만들고
go mod init home-cam
위 명령어로 프로젝트를 초기화 했다.
go get -u github.com/gin-gonic/gin
위 명령어로 gin package를 설치하고 아래와 같이 main.go를 작성해보자.
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// Create a new Gin router
router := gin.Default()
// Define a simple GET endpoint
router.GET("/hello", func(c *gin.Context) {
c.String(http.StatusOK, "Hello, World!")
})
// Start the server on port 8080
if err := router.Run(":8080"); err != nil {
fmt.Printf("Failed to start server: %v\n", err)
}
}
코파일럿의 도움을 받았지만 매우 간단하고 빠르고 이해하기도 쉽다.(web개발이 처음인 분들은 그렇지 않을 수 있다.)
주석에도 적혀있지만 코드는 크게 세 부분으로 나뉜다.
router를 생성하고, endpoint를 만들고 서버를 실행시킨다.
실행해보기
만들었으니깐 실행해보자.
vs code에선 디버깅도 쉽게 할 수 있다.
명령줄에서 go run main.go라고 쳐서 실행시킬 수 있지만 vs code의 디버깅 기능을 활용하자.
왼쪽에 Run & Debug tab을 누르고 create a lauch.json file을 선택하자.
go launch package를 선택하면 launch.json 파일이 생성된다.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/main.go",
}
]
}
위 처럼 수정하면 main.go를 실행시키고 디버깅을 시작할 수 있다.
terminal에서 아래와 같이 쳐보자
curl localhost:8080/hello
/hello endpoint로 요청을 보낸다.
그러면 우리가 /hello를 endpoint로 설정한 곳이 호출이되게 되고 결과로 Hello, World!를 받게 된다.
반응형
'Home Cam Service 개발하기' 카테고리의 다른 글
Handler test 작성 (1) | 2025.06.01 |
---|---|
gorm orm을 controller와 연결하기 (0) | 2025.05.31 |
gorm 사용하기(feat. sqlite3) (1) | 2025.05.29 |
사전준비 (0) | 2025.05.16 |