xxxxxxxxxx
type ApiResponse struct {
Code uint32
Message string
}
func main() {
router := http.NewServeMux()
router.HandleFunc("/", (func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(&ApiResponse{Code: http.StatusOK, Message: "Hello Wordl"})
}))
err := http.ListenAndServe(":3000", router)
if err != nil {
log.Fatal(err)
}
}
xxxxxxxxxx
// Code by Divyanshu Shekhar - https://divyanshushekhar.com/golang-http-server/
// Golang HTTP Server
package main
import (
"fmt"
"log"
"net/http"
)
const (
// Host name of the HTTP Server
Host = "localhost"
// Port of the HTTP Server
Port = "8080"
)
func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is a Simple HTTP Web Server!")
}
func main() {
http.HandleFunc("/", home)
err := http.ListenAndServe(Host+":"+Port, nil)
if err != nil {
log.Fatal("Error Starting the HTTP Server : ", err)
return
}
}
xxxxxxxxxx
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := map[string]string{"name": "john doe"}
json.NewEncoder(w).Encode(data)
})
http.ListenAndServe(":3000", nil)
xxxxxxxxxx
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"syscall"
"golang.org/x/sys/unix"
)
type Response struct {
StatCode uint `json:"stat_code"`
StatMsg string `json:"stat_msg"`
Data interface{} `json:"data,omitempty"`
}
func main() {
LoadEnvConfig()
s, n := Server()
s.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
res := Response{
StatCode: http.StatusOK,
StatMsg: "Golang application running using PM2",
}
json.NewEncoder(rw).Encode(&res)
})
err := http.Serve(n, s)
if err != nil {
log.Fatalf("Server listening error %v", err)
} else {
log.Printf("Server listening on port: %s", os.Getenv("GO_PORT"))
}
}
func Server() (*http.ServeMux, net.Listener) {
var lc = net.ListenConfig{
Control: func(network, address string, c syscall.RawConn) error {
err := c.Control(func(fd uintptr) {
err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
if err != nil {
log.Fatal(err)
}
})
if err != nil {
log.Fatal(err)
}
return nil
},
}
ln, err := lc.Listen(context.Background(), "tcp", fmt.Sprintf("127.0.0.1:%s", os.Getenv("GO_PORT")))
if err != nil {
log.Fatalf("Net listening error %v", err)
}
router := http.NewServeMux()
return router, ln
}
func LoadEnvConfig() {
_, bool := os.LookupEnv("GO_PORT")
if !bool {
os.Setenv("GO_PORT", "4000")
}
}
xxxxxxxxxx
package main
import (
"context"
"database/sql"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
_ "github.com/lib/pq"
migrate "github.com/rubenv/sql-migrate"
)
func main() {
SetupDatabase()
router := http.NewServeMux()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
fmt.Fprintln(w, map[string]interface{}{"data": "hello wordl"})
})
SetupGraceFullShutdown(router)
}
func SetupDatabase() *sql.DB {
driver_name := "postgres"
dsn_url := "postgres://admin:admin@localhost:5432/postgres?sslmode=disable"
migration_dir := "./database/migrations"
db, _ := sql.Open(driver_name, dsn_url)
if err := db.Ping(); err != nil {
log.Fatalf("Database connection error: %s", err.Error())
}
if os.Getenv("GO_ENV") == "development" {
migrations := migrate.FileMigrationSource{
Dir: migration_dir,
}
if _, err := migrations.FindMigrations(); err != nil {
log.Fatalf("Find migration database error: %s", err.Error())
}
if _, err := migrate.Exec(db, driver_name, migrations, migrate.Up); err != nil {
log.Fatalf("Execute migration database error: %s", err.Error())
}
}
defer log.Println("Database connection success")
return db
}
func SetupGraceFullShutdown(handler *http.ServeMux) {
httpServer := http.Server{
Addr: fmt.Sprintf(":%s", "3000"),
ReadTimeout: time.Duration(time.Second) * 60,
WriteTimeout: time.Duration(time.Second) * 30,
IdleTimeout: time.Duration(time.Second) * 120,
MaxHeaderBytes: 3145728,
Handler: handler,
}
if err := httpServer.ListenAndServe(); err != nil {
log.Fatalf("Server is not running: %s", err.Error())
os.Exit(0)
}
osSignal := make(chan os.Signal, 1)
signal.Notify(osSignal, os.Interrupt, syscall.SIGTERM)
log.Printf("Signal received: %v", <-osSignal)
if sig := <-osSignal; sig == os.Interrupt || sig == syscall.SIGTERM {
log.Println("Waiting to server shutdown")
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second)*10)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.Println("HTTP server shutdown error: %s", err.Error())
}
log.Println("HTTP server shutdown")
}
}