Skip to content

Commit

Permalink
added server using gorilla mux
Browse files Browse the repository at this point in the history
  • Loading branch information
KulwinderSingh07 committed Oct 22, 2023
1 parent f70aa08 commit 69347f6
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PORT=3001
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/KulwinderSingh07/POW-Blockchain

go 1.20

require (
github.com/gorilla/mux v1.8.0
github.com/joho/godotenv v1.5.1
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
54 changes: 54 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package main

import (
"encoding/json"
"io"
"log"
"net/http"
"os"
"time"

"github.com/gorilla/mux"
"github.com/joho/godotenv"
)

func main() {
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
log.Fatal(run())
}

func run() error {
mux := makeMuxRouter()
httpPort := os.Getenv("PORT")
log.Println("Http server Listening on port :", httpPort)
s := &http.Server{
Addr: ":" + httpPort,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if err := s.ListenAndServe(); err != nil {
return err
}
return nil
}

func testing(res http.ResponseWriter, req *http.Request) {
data, err := json.Marshal("hello")
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
io.WriteString(res, string(data))
}

func makeMuxRouter() http.Handler {
muxRouter := mux.NewRouter()
muxRouter.HandleFunc("/", testing).Methods("GET")
muxRouter.HandleFunc("/", testing).Methods("POST")
return muxRouter
}

0 comments on commit 69347f6

Please sign in to comment.