Skip to content

Commit

Permalink
upload: initial files added
Browse files Browse the repository at this point in the history
  • Loading branch information
sambhavsaxena committed Jul 19, 2023
1 parent 42206b2 commit 943f913
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module golang-loadbalancer

go 1.20
Binary file added golang-loadbalancer
Binary file not shown.
89 changes: 89 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package main

import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
)

type Server interface {
Address() string
IsAlive() bool
Serve(rw http.ResponseWriter, req *http.Request)
}

type simpleServer struct {
addr string
proxy *httputil.ReverseProxy
}

func (s *simpleServer) Address() string { return s.addr }

func (s *simpleServer) IsAlive() bool { return true }

func (s *simpleServer) Serve(rw http.ResponseWriter, req *http.Request) {
s.proxy.ServeHTTP(rw, req)
}

func newSimpleServer(addr string) *simpleServer {
serverUrl, err := url.Parse(addr)
handleErr(err)
return &simpleServer{
addr: addr,
proxy: httputil.NewSingleHostReverseProxy(serverUrl),
}
}

type LoadBalancer struct {
port string
roundRobinCount int
servers []Server
}

func NewLoadBalancer(port string, servers []Server) *LoadBalancer {
return &LoadBalancer{
port: port,
roundRobinCount: 0,
servers: servers,
}
}

func handleErr(err error) {
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
}

func (lb *LoadBalancer) getNextAvailableServer() Server {
server := lb.servers[lb.roundRobinCount%len(lb.servers)]
for !server.IsAlive() {
lb.roundRobinCount++
server = lb.servers[lb.roundRobinCount%len(lb.servers)]
}
lb.roundRobinCount++
return server
}

func (lb *LoadBalancer) serveProxy(rw http.ResponseWriter, req *http.Request) {
targetServer := lb.getNextAvailableServer()
fmt.Printf("forwarding request to address %q\n", targetServer.Address())
targetServer.Serve(rw, req)
}

func main() {
servers := []Server{
newSimpleServer("http://localhost:3001"),
newSimpleServer("http://localhost:3002"),
newSimpleServer("http://localhost:3003"),
}
lb := NewLoadBalancer("3000", servers)
handleRedirect := func(rw http.ResponseWriter, req *http.Request) {
lb.serveProxy(rw, req)
}
http.HandleFunc("/", handleRedirect)
fmt.Printf("serving requests at 'localhost:%s'\n", lb.port)
http.ListenAndServe(":"+lb.port, nil)
}

0 comments on commit 943f913

Please sign in to comment.