บันทึกไว้กันลืม ตัวอย่างการต่อ PostgreSQL


require

- gorilla/mux # manage route
- gorm #orm

  • import library
import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"github.com/joho/godotenv"

	"github.com/gorilla/mux"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"github.com/rs/cors"
)

  • create model struc
type User struct {
	gorm.Model
	
	Name string
}
  • init database
func init() {

	e := godotenv.Load() //Load .env file
	if e != nil {
		fmt.Print(e)
	}

	username := os.Getenv("db_user")
	password := os.Getenv("db_pass")
	dbName := os.Getenv("db_name")
	dbHost := os.Getenv("db_host")


	dbUri := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password) //Build connection string
	fmt.Println(dbUri)

	conn, err := gorm.Open("postgres", dbUri)
	if err != nil {
		fmt.Print(err)
	}

	db = conn
	db.Debug().AutoMigrate(&User{}) //Database migration
}
  • simple get all
func GetAll(w http.ResponseWriter, r *http.Request) {

	var user []User

	db.Find(&user)

	json.NewEncoder(w).Encode(&user)

}
  • main

func main() {
	router.HandleFunc("/users", GetAll).Methods("GET")
	handler := cors.Default().Handler(router)
	log.Println("listen port: 8080")
	http.ListenAndServe(":8080", handler)
}
  • all main.go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"github.com/joho/godotenv"

	"github.com/gorilla/mux"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	"github.com/rs/cors"
)

var db *gorm.DB //database
var err error

type User struct {
	gorm.Model

	Name string
}


func GetAll(w http.ResponseWriter, r *http.Request) {

	var user []User

	db.Find(&user)

	json.NewEncoder(w).Encode(&user)

}

func init() {

	e := godotenv.Load() //Load .env file
	if e != nil {
		fmt.Print(e)
	}

	username := os.Getenv("db_user")
	password := os.Getenv("db_pass")
	dbName := os.Getenv("db_name")
	dbHost := os.Getenv("db_host")


	dbUri := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password) //Build connection string
	fmt.Println(dbUri)

	conn, err := gorm.Open("postgres", dbUri)
	if err != nil {
		fmt.Print(err)
	}

	db = conn
	db.Debug().AutoMigrate(&User{}) //Database migration
}

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/users", GetAll).Methods("GET")
	handler := cors.Default().Handler(router)
	fmt.Println("listen port: 8080")
	http.ListenAndServe(":8080", handler)
}

$ go run .

  • try curl
$ curl 127.0.0.1:8080/user 
...
#ex
[
  {
    "ID": 1,
    "CreatedAt": xxx,
    "UpdatedAt": xxx,
    "DeletedAt": null,
    "Name": xxx
  }
]