generated from traPtitech/naro-template-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (62 loc) · 1.6 KB
/
main.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"database/sql"
"errors"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/labstack/echo/v4"
)
type City struct {
ID int `json:"ID,omitempty" db:"ID"`
Name string `json:"name,omitempty" db:"Name"`
CountryCode string `json:"countryCode,omitempty" db:"CountryCode"`
District string `json:"district,omitempty" db:"District"`
Population int `json:"population,omitempty" db:"Population"`
}
var (
db *sqlx.DB
)
func main() {
jst, err := time.LoadLocation("Asia/Tokyo")
if err != nil {
log.Fatal(err)
}
conf := mysql.Config{
User: os.Getenv("DB_USERNAME"),
Passwd: os.Getenv("DB_PASSWORD"),
Net: "tcp",
Addr: os.Getenv("DB_HOSTNAME") + ":" + os.Getenv("DB_PORT"),
DBName: os.Getenv("DB_DATABASE"),
ParseTime: true,
Collation: "utf8mb4_unicode_ci",
Loc: jst,
}
_db, err := sqlx.Open("mysql", conf.FormatDSN())
if err != nil {
log.Fatal(err)
}
log.Println("connected")
db = _db
e := echo.New()
e.GET("/cities/:cityName", getCityInfoHandler)
e.Start(":8080")
}
func getCityInfoHandler(c echo.Context) error {
cityName := c.Param("cityName")
log.Println(cityName)
var city City
err := db.Get(&city, "SELECT * FROM city WHERE Name=?", cityName)
if errors.Is(err, sql.ErrNoRows) {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("No such city Name = %s", cityName))
}
if err != nil {
log.Printf("DB Error: %s", err)
return echo.NewHTTPError(http.StatusInternalServerError, "internal server error")
}
return c.JSON(http.StatusOK, city)
}