Skip to content

Instantly share code, notes, and snippets.

@iporsut
Created May 6, 2018 13:20
Show Gist options
  • Select an option

  • Save iporsut/f349dc8ca3b16ee6fe901a55e51df551 to your computer and use it in GitHub Desktop.

Select an option

Save iporsut/f349dc8ca3b16ee6fe901a55e51df551 to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
"fmt"
"io"
"log"
"net/http"
)
// Business Logic
// Need some service to finding username by id
type UserService interface {
FindUsernameByID(id int) (string, error)
}
// Business Logic Flow
type DisplayUsername struct {
// Need UserService
UserService
// Need Writer
io.Writer
}
func (d *DisplayUsername) Display() {
userName, err := d.FindUsernameByID(10)
if err != nil {
fmt.Fprintln(d.Writer, "Not found user id 10")
return
}
fmt.Fprintln(d.Writer, "Name is ", userName)
}
// Implement UserService with DB
type PostgreSQLUserService struct {
DB *sql.DB
WithTX bool
}
func (us *PostgreSQLUserService) FindUsernameByID(id int) (string, error) {
var username string
if us.WithTX {
tx, err := us.DB.Begin()
if err != nil {
return "", err
}
defer tx.Rollback()
err = tx.QueryRow("select username from users where id = $1", id).Scan(&username)
if err != nil {
return "", err
}
err = tx.Commit()
if err != nil {
return "", err
}
return username, err
}
err := us.DB.QueryRow("select username from users where id = $1", id).Scan(&username)
return username, err
}
// Handler Layer
type DisplayUsernameHandler struct {
UserService
}
func (h *DisplayUsernameHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ds := DisplayUsername{
UserService: h.UserService,
Writer: w,
}
ds.Display()
}
// Main compose layer
func main() {
db, err := sql.Open("postgres", "postgresql://postgres@localhost?sslmode=disable")
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.HandleFunc("/username", DisplayUsernameHandler{
UserService: PostgreSQLUserService{
DB: db,
},
})
mux.HandleFunc("/withtxusername", DisplayUsernameHandler{
UserService: PostgreSQLUserService{
DB: db,
WithTx: true,
},
})
http.ListenAndServe(":8080", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment