HTTP Server in Go
Go: HTTP Server
Go provides a simple way to create HTTP servers using the net/http package. Here's an example of how to create a simple HTTP server that responds with a "Hello, World!" message:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)
}
This code creates an HTTP server that listens on port 8080
. When a request is received, the server calls the provided handler function, which writes the "Hello, World!" message to the response.
How to create a server with a custom handler and a logger middleware in Go?
You can also create more complex servers by adding additional handlers and middleware functions.
Here's an example of how to create a server with a custom handler and a logger middleware:-
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", myHandler)
logger := log.New(os.Stdout, "my-server: ", log.LstdFlags)
http.ListenAndServe(":8080", logMiddleware(logger, nil))
}
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func logMiddleware(logger *log.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Printf("Received %s request from %s", r.Method, r.RemoteAddr)
next.ServeHTTP(w, r)
})
}
This code defines a custom handler function (myHandler
) and a middleware function (logMiddleware
) that logs incoming requests before passing them on to the next handler. The server is created by calling ListenAndServe
with the logger middleware added to the default http.Handler
chain.
I hope that helps you get started with creating HTTP servers in Go! Let me know if you have any more questions.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go